CameraPage.tsx 37 KB

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