CameraPage.tsx 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861
  1. import { useState, useEffect, useRef, useCallback } from 'react';
  2. import { useParams, useSearchParams } from 'react-router-dom';
  3. import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
  4. import { useTranslation } from 'react-i18next';
  5. import { RefreshCw, AlertTriangle, Camera, Maximize, Minimize, WifiOff, ZoomIn, ZoomOut, Stethoscope } from 'lucide-react';
  6. import { api, getAuthToken, getStreamToken, withStreamToken } from '../api/client';
  7. import { useToast } from '../contexts/ToastContext';
  8. import { useAuth } from '../contexts/AuthContext';
  9. import { useStreamTokenSync } from '../hooks/useCameraStreamToken';
  10. import { ChamberLight } from '../components/icons/ChamberLight';
  11. import { SkipObjectsModal, SkipObjectsIcon } from '../components/SkipObjectsModal';
  12. import { CameraDiagnoseModal } from '../components/CameraDiagnoseModal';
  13. const MAX_RECONNECT_ATTEMPTS = 5;
  14. const INITIAL_RECONNECT_DELAY = 2000; // 2 seconds
  15. const MAX_RECONNECT_DELAY = 30000; // 30 seconds
  16. const STALL_CHECK_INTERVAL = 5000; // Check every 5 seconds
  17. export function CameraPage() {
  18. const { t } = useTranslation();
  19. const queryClient = useQueryClient();
  20. const { showToast } = useToast();
  21. const { hasPermission, authEnabled, user } = useAuth();
  22. const { printerId } = useParams<{ printerId: string }>();
  23. const id = parseInt(printerId || '0', 10);
  24. const [searchParams] = useSearchParams();
  25. const fpsParam = parseInt(searchParams.get('fps') || '15', 10);
  26. const fps = Math.min(Math.max(isNaN(fpsParam) ? 15 : fpsParam, 1), 30);
  27. // Subscribe to the stream-token query so this page re-renders once the token
  28. // arrives. useStreamTokenSync (mounted in App) already owns the fetch; this
  29. // useQuery call dedupes via the shared key and just reads the cached value.
  30. useStreamTokenSync();
  31. const { data: streamTokenData, isPending: streamTokenPending } = useQuery({
  32. queryKey: ['camera-stream-token', user?.id ?? null],
  33. queryFn: () => api.getCameraStreamToken(),
  34. enabled: authEnabled ? !!user : true,
  35. staleTime: 50 * 60 * 1000,
  36. });
  37. const streamTokenValue = streamTokenData?.token ?? getStreamToken();
  38. const [streamMode, setStreamMode] = useState<'stream' | 'snapshot'>('stream');
  39. const [showSkipObjectsModal, setShowSkipObjectsModal] = useState(false);
  40. const [showDiagnoseModal, setShowDiagnoseModal] = useState(false);
  41. const [streamError, setStreamError] = useState(false);
  42. const [streamLoading, setStreamLoading] = useState(true);
  43. const [imageKey, setImageKey] = useState(Date.now());
  44. const [transitioning, setTransitioning] = useState(false);
  45. const [isFullscreen, setIsFullscreen] = useState(false);
  46. const [reconnectAttempts, setReconnectAttempts] = useState(0);
  47. const [isReconnecting, setIsReconnecting] = useState(false);
  48. const [reconnectCountdown, setReconnectCountdown] = useState(0);
  49. const [zoomLevel, setZoomLevel] = useState(1);
  50. const [panOffset, setPanOffset] = useState({ x: 0, y: 0 });
  51. const [isPanning, setIsPanning] = useState(false);
  52. const [panStart, setPanStart] = useState({ x: 0, y: 0 });
  53. const [lastTouchDistance, setLastTouchDistance] = useState<number | null>(null);
  54. const [lastTouchCenter, setLastTouchCenter] = useState<{ x: number; y: number } | null>(null);
  55. const imgRef = useRef<HTMLImageElement>(null);
  56. const containerRef = useRef<HTMLDivElement>(null);
  57. const reconnectTimerRef = useRef<NodeJS.Timeout | null>(null);
  58. const countdownIntervalRef = useRef<NodeJS.Timeout | null>(null);
  59. const stallCheckIntervalRef = useRef<NodeJS.Timeout | null>(null);
  60. // Consecutive "stalled/inactive" status reads. We only reconnect after two
  61. // in a row (~10s) so a brief blip while the shared fan-out upstream is
  62. // starting up or handing over between viewers doesn't tear down a stream
  63. // that's about to deliver frames — the churn that stranded the P1S camera
  64. // black for ~20 min (#2521).
  65. const stallStrikesRef = useRef(0);
  66. // Fetch printer info for the title
  67. const { data: printer } = useQuery({
  68. queryKey: ['printer', id],
  69. queryFn: () => api.getPrinter(id),
  70. enabled: id > 0,
  71. });
  72. // Fetch printer status for light toggle and skip objects
  73. const { data: status } = useQuery({
  74. queryKey: ['printerStatus', id],
  75. queryFn: () => api.getPrinterStatus(id),
  76. refetchInterval: 30000,
  77. enabled: id > 0,
  78. });
  79. // Chamber light mutation with optimistic update
  80. const chamberLightMutation = useMutation({
  81. mutationFn: (on: boolean) => api.setChamberLight(id, on),
  82. onMutate: async (on) => {
  83. await queryClient.cancelQueries({ queryKey: ['printerStatus', id] });
  84. const previousStatus = queryClient.getQueryData(['printerStatus', id]);
  85. queryClient.setQueryData(['printerStatus', id], (old: typeof status) => ({
  86. ...old,
  87. chamber_light: on,
  88. }));
  89. return { previousStatus };
  90. },
  91. onSuccess: (_, on) => {
  92. showToast(`Chamber light ${on ? 'on' : 'off'}`);
  93. },
  94. onError: (error: Error, _, context) => {
  95. if (context?.previousStatus) {
  96. queryClient.setQueryData(['printerStatus', id], context.previousStatus);
  97. }
  98. showToast(error.message || t('printers.toast.failedToControlChamberLight'), 'error');
  99. },
  100. });
  101. const isPrintingWithObjects = (status?.state === 'RUNNING' || status?.state === 'PAUSE') && (status?.printable_objects_count ?? 0) >= 2;
  102. // Update document title
  103. useEffect(() => {
  104. if (printer) {
  105. document.title = `${printer.name} - Camera`;
  106. }
  107. return () => {
  108. document.title = 'Bambuddy';
  109. };
  110. }, [printer]);
  111. // Cleanup on unmount - stop the camera stream
  112. // Track if we've already sent the stop signal to avoid duplicate calls
  113. const stopSentRef = useRef(false);
  114. useEffect(() => {
  115. const stopUrl = `/api/v1/printers/${id}/camera/stop`;
  116. stopSentRef.current = false;
  117. const sendStopOnce = () => {
  118. if (id > 0 && !stopSentRef.current) {
  119. stopSentRef.current = true;
  120. const headers: Record<string, string> = {};
  121. const token = getAuthToken();
  122. if (token) headers['Authorization'] = `Bearer ${token}`;
  123. fetch(stopUrl, { method: 'POST', keepalive: true, headers }).catch(() => {});
  124. }
  125. };
  126. // Handle page unload/close with keepalive fetch (more reliable than sendBeacon, supports auth)
  127. const handleBeforeUnload = () => {
  128. sendStopOnce();
  129. };
  130. window.addEventListener('beforeunload', handleBeforeUnload);
  131. // Store ref value for cleanup - ref may change by cleanup time
  132. const imgElement = imgRef.current;
  133. return () => {
  134. window.removeEventListener('beforeunload', handleBeforeUnload);
  135. // Clear the image source first to stop the stream
  136. if (imgElement) {
  137. imgElement.src = '';
  138. }
  139. // Send stop signal only once
  140. sendStopOnce();
  141. };
  142. }, [id]);
  143. // Auto-hide loading after timeout
  144. useEffect(() => {
  145. if (streamLoading && !transitioning) {
  146. const timeout = streamMode === 'stream' ? 3000 : 20000;
  147. const timer = setTimeout(() => {
  148. setStreamLoading(false);
  149. }, timeout);
  150. return () => clearTimeout(timer);
  151. }
  152. }, [streamMode, streamLoading, imageKey, transitioning]);
  153. // Fullscreen change listener - refresh stream after fullscreen transition
  154. useEffect(() => {
  155. const handleFullscreenChange = () => {
  156. const nowFullscreen = !!document.fullscreenElement;
  157. setIsFullscreen(nowFullscreen);
  158. // Reset zoom on fullscreen transition
  159. setZoomLevel(1);
  160. setPanOffset({ x: 0, y: 0 });
  161. // Refresh stream after fullscreen transition to prevent stall
  162. if (streamMode === 'stream' && !transitioning) {
  163. // Clear image src first, then set new key after delay
  164. if (imgRef.current) {
  165. imgRef.current.src = '';
  166. }
  167. setTimeout(() => {
  168. setStreamLoading(true);
  169. setImageKey(Date.now());
  170. }, 200);
  171. }
  172. };
  173. document.addEventListener('fullscreenchange', handleFullscreenChange);
  174. return () => document.removeEventListener('fullscreenchange', handleFullscreenChange);
  175. }, [streamMode, transitioning]);
  176. // Save window size and position when user resizes or moves
  177. // Works for both popup windows and standalone camera pages
  178. useEffect(() => {
  179. let saveTimeout: NodeJS.Timeout;
  180. const saveWindowState = () => {
  181. // Debounce to avoid saving during drag
  182. clearTimeout(saveTimeout);
  183. saveTimeout = setTimeout(() => {
  184. localStorage.setItem('cameraWindowState', JSON.stringify({
  185. width: window.outerWidth,
  186. height: window.outerHeight,
  187. left: window.screenX,
  188. top: window.screenY,
  189. }));
  190. }, 500);
  191. };
  192. window.addEventListener('resize', saveWindowState);
  193. return () => {
  194. clearTimeout(saveTimeout);
  195. window.removeEventListener('resize', saveWindowState);
  196. };
  197. }, []);
  198. // Clean up reconnect timers on unmount
  199. useEffect(() => {
  200. return () => {
  201. if (reconnectTimerRef.current) {
  202. clearTimeout(reconnectTimerRef.current);
  203. }
  204. if (countdownIntervalRef.current) {
  205. clearInterval(countdownIntervalRef.current);
  206. }
  207. if (stallCheckIntervalRef.current) {
  208. clearInterval(stallCheckIntervalRef.current);
  209. }
  210. };
  211. }, []);
  212. // Auto-reconnect logic
  213. const attemptReconnect = useCallback(() => {
  214. if (reconnectAttempts >= MAX_RECONNECT_ATTEMPTS) {
  215. setIsReconnecting(false);
  216. setStreamError(true);
  217. return;
  218. }
  219. // Calculate delay with exponential backoff
  220. const delay = Math.min(
  221. INITIAL_RECONNECT_DELAY * Math.pow(2, reconnectAttempts),
  222. MAX_RECONNECT_DELAY
  223. );
  224. setIsReconnecting(true);
  225. setReconnectCountdown(Math.ceil(delay / 1000));
  226. // Countdown timer
  227. countdownIntervalRef.current = setInterval(() => {
  228. setReconnectCountdown((prev) => {
  229. if (prev <= 1) {
  230. if (countdownIntervalRef.current) {
  231. clearInterval(countdownIntervalRef.current);
  232. }
  233. return 0;
  234. }
  235. return prev - 1;
  236. });
  237. }, 1000);
  238. // Reconnect after delay
  239. reconnectTimerRef.current = setTimeout(() => {
  240. setReconnectAttempts((prev) => prev + 1);
  241. setIsReconnecting(false);
  242. setStreamLoading(true);
  243. setStreamError(false);
  244. if (imgRef.current) {
  245. imgRef.current.src = '';
  246. }
  247. setImageKey(Date.now());
  248. }, delay);
  249. }, [reconnectAttempts]);
  250. // Stall detection - periodically check if stream is still receiving frames
  251. useEffect(() => {
  252. // Only skip stall check during initial load, reconnecting, or transitioning
  253. // Continue checking even during streamError to detect recovery
  254. if (streamMode !== 'stream' || streamLoading || isReconnecting || transitioning) {
  255. if (stallCheckIntervalRef.current) {
  256. clearInterval(stallCheckIntervalRef.current);
  257. stallCheckIntervalRef.current = null;
  258. }
  259. return;
  260. }
  261. // Start stall detection after stream has loaded. Reset the strike counter
  262. // so a fresh load doesn't inherit strikes from a previous stall episode.
  263. stallStrikesRef.current = 0;
  264. stallCheckIntervalRef.current = setInterval(async () => {
  265. try {
  266. const status = await api.getCameraStatus(id);
  267. // A "bad" read is: backend reports stall (no frames for 10+ seconds),
  268. // OR the stream is no longer active (process died).
  269. const bad = status.stalled || (!status.active && !streamError);
  270. if (!bad) {
  271. stallStrikesRef.current = 0;
  272. return;
  273. }
  274. stallStrikesRef.current += 1;
  275. // Require two consecutive bad reads before acting (#2521) — one blip
  276. // during fan-out startup/handover is not a real stall.
  277. if (stallStrikesRef.current < 2) {
  278. return;
  279. }
  280. stallStrikesRef.current = 0;
  281. console.log(`Stream issue detected: stalled=${status.stalled}, active=${status.active}, reconnecting...`);
  282. if (stallCheckIntervalRef.current) {
  283. clearInterval(stallCheckIntervalRef.current);
  284. stallCheckIntervalRef.current = null;
  285. }
  286. setStreamLoading(false);
  287. attemptReconnect();
  288. } catch {
  289. // Ignore fetch errors - server might be temporarily unavailable
  290. }
  291. }, STALL_CHECK_INTERVAL);
  292. return () => {
  293. if (stallCheckIntervalRef.current) {
  294. clearInterval(stallCheckIntervalRef.current);
  295. stallCheckIntervalRef.current = null;
  296. }
  297. };
  298. }, [streamMode, streamLoading, streamError, isReconnecting, transitioning, id, attemptReconnect]);
  299. const handleStreamError = () => {
  300. setStreamLoading(false);
  301. // Only auto-reconnect for live stream mode
  302. if (streamMode === 'stream' && reconnectAttempts < MAX_RECONNECT_ATTEMPTS) {
  303. attemptReconnect();
  304. } else {
  305. setStreamError(true);
  306. }
  307. };
  308. const handleStreamLoad = () => {
  309. setStreamLoading(false);
  310. setStreamError(false);
  311. // Reset reconnect attempts on successful connection
  312. setReconnectAttempts(0);
  313. // A frame rendered — clear any accumulated stall strikes (#2521).
  314. stallStrikesRef.current = 0;
  315. setIsReconnecting(false);
  316. if (reconnectTimerRef.current) {
  317. clearTimeout(reconnectTimerRef.current);
  318. }
  319. if (countdownIntervalRef.current) {
  320. clearInterval(countdownIntervalRef.current);
  321. }
  322. // Auto-resize window to fit video content (only if no saved preference)
  323. if (imgRef.current && !localStorage.getItem('cameraWindowState')) {
  324. const img = imgRef.current;
  325. const videoWidth = img.naturalWidth;
  326. const videoHeight = img.naturalHeight;
  327. if (videoWidth > 0 && videoHeight > 0) {
  328. // Add space for header bar (~45px) and some padding
  329. const headerHeight = 45;
  330. const padding = 16;
  331. // Calculate window size (outer size includes chrome)
  332. const chromeWidth = window.outerWidth - window.innerWidth;
  333. const chromeHeight = window.outerHeight - window.innerHeight;
  334. const targetWidth = videoWidth + padding + chromeWidth;
  335. const targetHeight = videoHeight + headerHeight + padding + chromeHeight;
  336. try {
  337. window.resizeTo(targetWidth, targetHeight);
  338. } catch {
  339. // resizeTo may not be allowed in all contexts
  340. }
  341. }
  342. }
  343. };
  344. const stopStream = () => {
  345. if (id > 0) {
  346. const headers: Record<string, string> = {};
  347. const token = getAuthToken();
  348. if (token) headers['Authorization'] = `Bearer ${token}`;
  349. fetch(`/api/v1/printers/${id}/camera/stop`, { method: 'POST', headers }).catch(() => {});
  350. }
  351. };
  352. const switchToMode = (newMode: 'stream' | 'snapshot') => {
  353. if (streamMode === newMode || transitioning) return;
  354. setTransitioning(true);
  355. setStreamLoading(true);
  356. setStreamError(false);
  357. // Reset reconnect state on mode switch
  358. setReconnectAttempts(0);
  359. setIsReconnecting(false);
  360. // Reset zoom on mode switch
  361. setZoomLevel(1);
  362. setPanOffset({ x: 0, y: 0 });
  363. if (reconnectTimerRef.current) {
  364. clearTimeout(reconnectTimerRef.current);
  365. }
  366. if (countdownIntervalRef.current) {
  367. clearInterval(countdownIntervalRef.current);
  368. }
  369. if (imgRef.current) {
  370. imgRef.current.src = '';
  371. }
  372. // Stop any active streams when switching modes
  373. if (streamMode === 'stream') {
  374. stopStream();
  375. }
  376. setTimeout(() => {
  377. setStreamMode(newMode);
  378. setImageKey(Date.now());
  379. setTransitioning(false);
  380. }, 100);
  381. };
  382. const refresh = () => {
  383. if (transitioning) return;
  384. setTransitioning(true);
  385. setStreamLoading(true);
  386. setStreamError(false);
  387. // Reset reconnect state on manual refresh
  388. setReconnectAttempts(0);
  389. setIsReconnecting(false);
  390. if (reconnectTimerRef.current) {
  391. clearTimeout(reconnectTimerRef.current);
  392. }
  393. if (countdownIntervalRef.current) {
  394. clearInterval(countdownIntervalRef.current);
  395. }
  396. if (imgRef.current) {
  397. imgRef.current.src = '';
  398. }
  399. // Stop any active streams before refresh
  400. if (streamMode === 'stream') {
  401. stopStream();
  402. }
  403. setTimeout(() => {
  404. setImageKey(Date.now());
  405. setTransitioning(false);
  406. }, 100);
  407. };
  408. const toggleFullscreen = () => {
  409. if (!containerRef.current) return;
  410. if (document.fullscreenElement) {
  411. document.exitFullscreen();
  412. } else {
  413. containerRef.current.requestFullscreen();
  414. }
  415. };
  416. const handleZoomIn = () => {
  417. setZoomLevel(prev => Math.min(prev + 0.5, 4));
  418. };
  419. const handleZoomOut = () => {
  420. setZoomLevel(prev => {
  421. const newZoom = Math.max(prev - 0.5, 1);
  422. if (newZoom === 1) setPanOffset({ x: 0, y: 0 });
  423. return newZoom;
  424. });
  425. };
  426. const handleWheel = (e: React.WheelEvent) => {
  427. e.preventDefault();
  428. if (e.deltaY < 0) {
  429. handleZoomIn();
  430. } else {
  431. handleZoomOut();
  432. }
  433. };
  434. const handleImageMouseDown = (e: React.MouseEvent) => {
  435. if (zoomLevel > 1) {
  436. e.preventDefault();
  437. setIsPanning(true);
  438. setPanStart({ x: e.clientX - panOffset.x, y: e.clientY - panOffset.y });
  439. }
  440. };
  441. // Calculate max pan based on container size and zoom level
  442. const getMaxPan = useCallback(() => {
  443. if (!containerRef.current) {
  444. return { x: 300, y: 200 };
  445. }
  446. const container = containerRef.current.getBoundingClientRect();
  447. // Allow panning up to half the zoomed overflow in each direction
  448. const maxX = (container.width * (zoomLevel - 1)) / 2;
  449. const maxY = (container.height * (zoomLevel - 1)) / 2;
  450. return { x: Math.max(50, maxX), y: Math.max(50, maxY) };
  451. }, [zoomLevel]);
  452. const handleImageMouseMove = (e: React.MouseEvent) => {
  453. if (isPanning && zoomLevel > 1) {
  454. const newX = e.clientX - panStart.x;
  455. const newY = e.clientY - panStart.y;
  456. const maxPan = getMaxPan();
  457. setPanOffset({
  458. x: Math.max(-maxPan.x, Math.min(maxPan.x, newX)),
  459. y: Math.max(-maxPan.y, Math.min(maxPan.y, newY)),
  460. });
  461. }
  462. };
  463. const handleImageMouseUp = () => {
  464. setIsPanning(false);
  465. };
  466. // Touch event handlers for mobile
  467. const getTouchDistance = (touches: React.TouchList) => {
  468. if (touches.length < 2) return 0;
  469. const dx = touches[0].clientX - touches[1].clientX;
  470. const dy = touches[0].clientY - touches[1].clientY;
  471. return Math.sqrt(dx * dx + dy * dy);
  472. };
  473. const getTouchCenter = (touches: React.TouchList) => {
  474. if (touches.length < 2) {
  475. return { x: touches[0].clientX, y: touches[0].clientY };
  476. }
  477. return {
  478. x: (touches[0].clientX + touches[1].clientX) / 2,
  479. y: (touches[0].clientY + touches[1].clientY) / 2,
  480. };
  481. };
  482. const handleTouchStart = (e: React.TouchEvent) => {
  483. if (e.touches.length === 2) {
  484. // Pinch gesture start
  485. e.preventDefault();
  486. setLastTouchDistance(getTouchDistance(e.touches));
  487. setLastTouchCenter(getTouchCenter(e.touches));
  488. } else if (e.touches.length === 1 && zoomLevel > 1) {
  489. // Single touch pan start
  490. e.preventDefault();
  491. setIsPanning(true);
  492. setPanStart({
  493. x: e.touches[0].clientX - panOffset.x,
  494. y: e.touches[0].clientY - panOffset.y,
  495. });
  496. }
  497. };
  498. const handleTouchMove = (e: React.TouchEvent) => {
  499. if (e.touches.length === 2 && lastTouchDistance !== null) {
  500. // Pinch gesture
  501. e.preventDefault();
  502. const newDistance = getTouchDistance(e.touches);
  503. const scale = newDistance / lastTouchDistance;
  504. setZoomLevel(prev => {
  505. const newZoom = Math.max(1, Math.min(4, prev * scale));
  506. if (newZoom === 1) {
  507. setPanOffset({ x: 0, y: 0 });
  508. }
  509. return newZoom;
  510. });
  511. setLastTouchDistance(newDistance);
  512. // Also handle pan during pinch
  513. const newCenter = getTouchCenter(e.touches);
  514. if (lastTouchCenter) {
  515. const maxPan = getMaxPan();
  516. setPanOffset(prev => ({
  517. x: Math.max(-maxPan.x, Math.min(maxPan.x, prev.x + (newCenter.x - lastTouchCenter.x))),
  518. y: Math.max(-maxPan.y, Math.min(maxPan.y, prev.y + (newCenter.y - lastTouchCenter.y))),
  519. }));
  520. }
  521. setLastTouchCenter(newCenter);
  522. } else if (e.touches.length === 1 && isPanning && zoomLevel > 1) {
  523. // Single touch pan
  524. e.preventDefault();
  525. const newX = e.touches[0].clientX - panStart.x;
  526. const newY = e.touches[0].clientY - panStart.y;
  527. const maxPan = getMaxPan();
  528. setPanOffset({
  529. x: Math.max(-maxPan.x, Math.min(maxPan.x, newX)),
  530. y: Math.max(-maxPan.y, Math.min(maxPan.y, newY)),
  531. });
  532. }
  533. };
  534. const handleTouchEnd = (e: React.TouchEvent) => {
  535. if (e.touches.length < 2) {
  536. setLastTouchDistance(null);
  537. setLastTouchCenter(null);
  538. }
  539. if (e.touches.length === 0) {
  540. setIsPanning(false);
  541. }
  542. };
  543. const resetZoom = () => {
  544. setZoomLevel(1);
  545. setPanOffset({ x: 0, y: 0 });
  546. };
  547. // When auth is enabled, wait for the stream token before rendering the <img>
  548. // src — otherwise the first request fires without ?token= and the backend
  549. // rejects it with "Valid camera stream token required" (see #979). We append
  550. // the token directly from the reactive query value instead of relying on the
  551. // module-level cache in withStreamToken(), because that cache is updated in a
  552. // useEffect that runs after render.
  553. //
  554. // We also wait when auth is *disabled* (#2521). The token query runs either
  555. // way, and this page subscribes to it — so the first render produced a src
  556. // with no token, the token landed, and the re-render CHANGED img.src. The
  557. // browser aborts the in-flight request and issues a second one. With auth off
  558. // no token is required, so *both* reached the backend and attached to the
  559. // fan-out: every page load added two viewers and abandoned one of them. Wait
  560. // for the query to settle and there is one src, one request, one viewer.
  561. // Falling through once it has settled without a token keeps an auth-disabled
  562. // install working even if the token endpoint fails — it doesn't need one.
  563. const waitingForStreamToken = !streamTokenValue && (authEnabled || streamTokenPending);
  564. const appendToken = (url: string) =>
  565. streamTokenValue ? `${url}&token=${encodeURIComponent(streamTokenValue)}` : withStreamToken(url);
  566. const currentUrl = transitioning || waitingForStreamToken
  567. ? ''
  568. : streamMode === 'stream'
  569. ? appendToken(`/api/v1/printers/${id}/camera/stream?fps=${fps}&t=${imageKey}`)
  570. : appendToken(`/api/v1/printers/${id}/camera/snapshot?t=${imageKey}`);
  571. const isDisabled = streamLoading || transitioning || isReconnecting;
  572. if (!id) {
  573. return (
  574. <div className="min-h-screen bg-black flex items-center justify-center">
  575. <p className="text-white">{t('camera.invalidPrinterId')}</p>
  576. </div>
  577. );
  578. }
  579. return (
  580. <div ref={containerRef} className="min-h-screen bg-black flex flex-col">
  581. {/* Header */}
  582. <div className="flex items-center justify-between px-4 py-2 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary">
  583. <h1 className="text-sm font-medium text-white flex items-center gap-2">
  584. <Camera className="w-4 h-4" />
  585. {printer?.name || `Printer ${id}`}
  586. </h1>
  587. <div className="flex items-center gap-2">
  588. {/* Mode toggle */}
  589. <div className="flex bg-bambu-dark rounded p-0.5">
  590. <button
  591. onClick={() => switchToMode('stream')}
  592. disabled={isDisabled}
  593. className={`px-3 py-1 text-xs rounded transition-colors ${
  594. streamMode === 'stream'
  595. ? 'bg-bambu-green text-white'
  596. : 'text-bambu-gray hover:text-white disabled:opacity-50'
  597. }`}
  598. >
  599. {t('camera.live')}
  600. </button>
  601. <button
  602. onClick={() => switchToMode('snapshot')}
  603. disabled={isDisabled}
  604. className={`px-3 py-1 text-xs rounded transition-colors ${
  605. streamMode === 'snapshot'
  606. ? 'bg-bambu-green text-white'
  607. : 'text-bambu-gray hover:text-white disabled:opacity-50'
  608. }`}
  609. >
  610. {t('camera.snapshot')}
  611. </button>
  612. </div>
  613. <button
  614. onClick={() => chamberLightMutation.mutate(!status?.chamber_light)}
  615. disabled={!status?.connected || chamberLightMutation.isPending || !hasPermission('printers:control')}
  616. className={`p-1.5 rounded disabled:opacity-50 ${status?.chamber_light ? 'bg-yellow-500/20 hover:bg-yellow-500/30' : 'hover:bg-bambu-dark-tertiary'}`}
  617. title={!hasPermission('printers:control') ? t('printers.permission.noControl') : t('camera.chamberLight')}
  618. >
  619. <ChamberLight on={status?.chamber_light ?? false} className="w-4 h-4" />
  620. </button>
  621. <button
  622. onClick={() => setShowSkipObjectsModal(true)}
  623. disabled={!isPrintingWithObjects || !hasPermission('printers:control')}
  624. className={`p-1.5 rounded disabled:opacity-50 ${isPrintingWithObjects && hasPermission('printers:control') ? 'hover:bg-bambu-dark-tertiary' : ''}`}
  625. title={
  626. !hasPermission('printers:control')
  627. ? t('printers.permission.noControl')
  628. : !isPrintingWithObjects
  629. ? t('printers.skipObjects.onlyWhilePrinting')
  630. : t('printers.skipObjects.tooltip')
  631. }
  632. >
  633. <SkipObjectsIcon className="w-4 h-4 text-bambu-gray" />
  634. </button>
  635. <button
  636. onClick={refresh}
  637. disabled={isDisabled}
  638. className="p-1.5 hover:bg-bambu-dark-tertiary rounded disabled:opacity-50"
  639. title={streamMode === 'stream' ? t('camera.restartStream') : t('camera.refreshSnapshot')}
  640. >
  641. <RefreshCw className={`w-4 h-4 text-bambu-gray ${isDisabled ? 'animate-spin' : ''}`} />
  642. </button>
  643. <button
  644. onClick={() => setShowDiagnoseModal(true)}
  645. className="p-1.5 hover:bg-bambu-dark-tertiary rounded"
  646. title={t('camera.diagnose.button')}
  647. >
  648. <Stethoscope className="w-4 h-4 text-bambu-gray" />
  649. </button>
  650. <button
  651. onClick={toggleFullscreen}
  652. className="p-1.5 hover:bg-bambu-dark-tertiary rounded"
  653. title={isFullscreen ? t('camera.exitFullscreen') : t('camera.fullscreen')}
  654. >
  655. {isFullscreen ? (
  656. <Minimize className="w-4 h-4 text-bambu-gray" />
  657. ) : (
  658. <Maximize className="w-4 h-4 text-bambu-gray" />
  659. )}
  660. </button>
  661. </div>
  662. </div>
  663. {/* Video area */}
  664. <div
  665. className="flex-1 flex items-center justify-center p-2 overflow-hidden"
  666. onWheel={handleWheel}
  667. onMouseMove={handleImageMouseMove}
  668. onMouseUp={handleImageMouseUp}
  669. onMouseLeave={handleImageMouseUp}
  670. onTouchStart={handleTouchStart}
  671. onTouchMove={handleTouchMove}
  672. onTouchEnd={handleTouchEnd}
  673. style={{ touchAction: 'none' }}
  674. >
  675. <div className="relative w-full h-full flex items-center justify-center">
  676. {(streamLoading || transitioning) && !isReconnecting && (
  677. <div className="absolute inset-0 flex items-center justify-center bg-black/50 z-10">
  678. <div className="text-center">
  679. <RefreshCw className="w-8 h-8 text-bambu-gray animate-spin mx-auto mb-2" />
  680. <p className="text-sm text-bambu-gray">
  681. {streamMode === 'stream' ? t('camera.connectingToCamera') : t('camera.capturingSnapshot')}
  682. </p>
  683. </div>
  684. </div>
  685. )}
  686. {isReconnecting && (
  687. <div className="absolute inset-0 flex items-center justify-center bg-black/80 z-10">
  688. <div className="text-center p-4">
  689. <WifiOff className="w-10 h-10 text-orange-400 mx-auto mb-3" />
  690. <p className="text-white mb-2">{t('camera.connectionLost')}</p>
  691. <p className="text-sm text-bambu-gray mb-3">
  692. {t('camera.reconnecting', { countdown: reconnectCountdown, attempt: Math.min(reconnectAttempts + 1, MAX_RECONNECT_ATTEMPTS), max: MAX_RECONNECT_ATTEMPTS })}
  693. </p>
  694. <button
  695. onClick={refresh}
  696. className="px-4 py-2 bg-bambu-green text-white text-sm rounded hover:bg-bambu-green/80 transition-colors"
  697. >
  698. {t('camera.reconnectNow')}
  699. </button>
  700. </div>
  701. </div>
  702. )}
  703. {streamError && !isReconnecting && (
  704. <div className="absolute inset-0 flex items-center justify-center bg-black z-10">
  705. <div className="text-center p-4">
  706. <AlertTriangle className="w-12 h-12 text-orange-400 mx-auto mb-3" />
  707. <p className="text-white mb-2">{t('camera.cameraUnavailable')}</p>
  708. <p className="text-xs text-bambu-gray mb-4 max-w-md">
  709. {t('camera.cameraUnavailableDesc')}
  710. </p>
  711. <div className="flex gap-2 justify-center">
  712. <button
  713. onClick={refresh}
  714. className="px-4 py-2 bg-bambu-green text-white rounded hover:bg-bambu-green/80 transition-colors"
  715. >
  716. {t('camera.retry')}
  717. </button>
  718. <button
  719. onClick={() => setShowDiagnoseModal(true)}
  720. className="px-4 py-2 bg-bambu-dark border border-bambu-dark-tertiary text-bambu-gray hover:text-white rounded transition-colors"
  721. >
  722. {t('camera.diagnose.button')}
  723. </button>
  724. </div>
  725. </div>
  726. </div>
  727. )}
  728. <img
  729. ref={imgRef}
  730. key={imageKey}
  731. src={currentUrl}
  732. alt={t('camera.cameraStream')}
  733. className="max-w-full max-h-full object-contain select-none"
  734. style={{
  735. transform: `scale(${zoomLevel}) translate(${panOffset.x / zoomLevel}px, ${panOffset.y / zoomLevel}px) rotate(${printer?.camera_rotation || 0}deg)`,
  736. ...(printer?.camera_rotation === 90 || printer?.camera_rotation === 270 ? { maxWidth: '100vh', maxHeight: '100vw' } : {}),
  737. cursor: zoomLevel > 1 ? (isPanning ? 'grabbing' : 'grab') : 'default',
  738. }}
  739. onError={currentUrl ? handleStreamError : undefined}
  740. onLoad={currentUrl ? handleStreamLoad : undefined}
  741. onMouseDown={handleImageMouseDown}
  742. draggable={false}
  743. />
  744. {/* Zoom controls */}
  745. <div className="absolute bottom-4 left-4 flex items-center gap-1.5 bg-black/60 rounded-lg px-2 py-1.5">
  746. <button
  747. onClick={handleZoomOut}
  748. disabled={zoomLevel <= 1}
  749. className="p-1.5 hover:bg-white/10 rounded disabled:opacity-30"
  750. title={t('camera.zoomOut')}
  751. >
  752. <ZoomOut className="w-4 h-4 text-white" />
  753. </button>
  754. <button
  755. onClick={resetZoom}
  756. className="px-2 py-1 text-sm text-white hover:bg-white/10 rounded min-w-[48px]"
  757. title={t('camera.resetZoom')}
  758. >
  759. {Math.round(zoomLevel * 100)}%
  760. </button>
  761. <button
  762. onClick={handleZoomIn}
  763. disabled={zoomLevel >= 4}
  764. className="p-1.5 hover:bg-white/10 rounded disabled:opacity-30"
  765. title={t('camera.zoomIn')}
  766. >
  767. <ZoomIn className="w-4 h-4 text-white" />
  768. </button>
  769. </div>
  770. </div>
  771. </div>
  772. {/* Skip Objects Modal */}
  773. <SkipObjectsModal
  774. printerId={id}
  775. isOpen={showSkipObjectsModal}
  776. onClose={() => setShowSkipObjectsModal(false)}
  777. />
  778. {/* Camera diagnostic modal — stethoscope icon + error-state Diagnose button (#1395) */}
  779. {showDiagnoseModal && (
  780. <CameraDiagnoseModal
  781. printerId={id}
  782. printerName={printer?.name || null}
  783. onClose={() => setShowDiagnoseModal(false)}
  784. />
  785. )}
  786. </div>
  787. );
  788. }