CameraPage.tsx 32 KB

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