CameraPage.tsx 30 KB

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