camera.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. /**
  2. * How a camera stream opens: a separate browser window, or a floating overlay
  3. * on the page you are already on.
  4. *
  5. * This used to be one global switch in Settings > General > Camera. It is now
  6. * chosen per click from the camera button's own menu, and the stored setting
  7. * survives only as the default a browser starts from.
  8. */
  9. export type CameraViewMode = 'window' | 'embedded';
  10. /** The mode the last camera button click chose, in this browser. */
  11. const CAMERA_VIEW_MODE_KEY = 'cameraViewMode';
  12. /** Geometry the camera popup was last left at, written by CameraPage. */
  13. const CAMERA_WINDOW_STATE_KEY = 'cameraWindowState';
  14. export function isCameraViewMode(value: unknown): value is CameraViewMode {
  15. return value === 'window' || value === 'embedded';
  16. }
  17. /**
  18. * The local choice, or null if this browser has never made one.
  19. *
  20. * Null rather than a default so the caller can fall back to the server-side
  21. * setting: that is what makes a fresh browser open the same way the last one
  22. * did, without the local choice ever being overwritten by it.
  23. */
  24. export function readStoredCameraViewMode(): CameraViewMode | null {
  25. try {
  26. const saved = localStorage.getItem(CAMERA_VIEW_MODE_KEY);
  27. return isCameraViewMode(saved) ? saved : null;
  28. } catch {
  29. // Private-mode Safari and friends. A camera that opens the default way is
  30. // a better outcome than a page that throws on render.
  31. return null;
  32. }
  33. }
  34. export function storeCameraViewMode(mode: CameraViewMode): void {
  35. try {
  36. localStorage.setItem(CAMERA_VIEW_MODE_KEY, mode);
  37. } catch {
  38. // Choice applies to this session regardless; only persistence is lost.
  39. }
  40. }
  41. /**
  42. * True in a web app started from the iOS home screen ("Add to Home Screen").
  43. *
  44. * There is no second window to open there: iOS loads a `window.open` URL into
  45. * the app itself, full screen, and the camera page it showed had no way back
  46. * to the rest of Bambuddy (#3419). Cameras open as the overlay instead.
  47. *
  48. * iOS only, deliberately not `display-mode: standalone`: Bambuddy installed as
  49. * an app on a desktop opens a real popup window, and Android a closable
  50. * in-app browser, so their window mode works and stays.
  51. */
  52. export function isStandaloneWebApp(): boolean {
  53. try {
  54. return (navigator as Navigator & { standalone?: boolean }).standalone === true;
  55. } catch {
  56. return false;
  57. }
  58. }
  59. /**
  60. * Open a printer's camera in its own browser window, reusing whatever size and
  61. * position the user last left one at.
  62. *
  63. * Deliberately not `noopener`: the popup is same-origin and needs `opener` set
  64. * so the browser copies sessionStorage -- which is where the auth token lives
  65. * -- into the new window. Without it the camera page loads unauthenticated.
  66. */
  67. export function openCameraWindow(printerId: number): boolean {
  68. let state: { width?: number; height?: number; left?: number; top?: number } = {
  69. width: 640,
  70. height: 400,
  71. };
  72. try {
  73. const saved = localStorage.getItem(CAMERA_WINDOW_STATE_KEY);
  74. if (saved) {
  75. const parsed = JSON.parse(saved) as typeof state;
  76. if (parsed && typeof parsed === 'object') state = parsed;
  77. }
  78. } catch {
  79. // Corrupt or unreadable geometry falls back to the defaults above rather
  80. // than leaving the camera unopenable.
  81. }
  82. const features = [
  83. `width=${state.width ?? 640}`,
  84. `height=${state.height ?? 400}`,
  85. state.left !== undefined ? `left=${state.left}` : '',
  86. state.top !== undefined ? `top=${state.top}` : '',
  87. 'menubar=no,toolbar=no,location=no,status=no',
  88. ]
  89. .filter(Boolean)
  90. .join(',');
  91. // False when a popup blocker stopped it, so a caller closing the overlay it
  92. // came from can leave the camera where it was.
  93. return window.open(`/camera/${printerId}`, `camera-${printerId}`, features) !== null;
  94. }
  95. /**
  96. * Moving a camera window back into a Bambuddy tab as an overlay (#2737).
  97. *
  98. * The camera window asks over a BroadcastChannel, every tab showing the app
  99. * answers, and exactly one of them is told to open the overlay: a window can
  100. * be open beside several tabs, and the camera should not appear in each.
  101. * The tab the window was opened from is preferred. Its id is in
  102. * sessionStorage, which the browser copies into the popup when it opens.
  103. */
  104. const CAMERA_CHANNEL = 'bambuddy-camera';
  105. const TAB_ID_KEY = 'bambuddyTabId';
  106. type PopInMessage =
  107. | { type: 'pop-in-offer'; requestId: string; printerId: number; printerName: string }
  108. | { type: 'pop-in-candidate'; requestId: string; tabId: string; instanceId: string }
  109. | { type: 'pop-in-claim'; requestId: string; instanceId: string; deadline: number }
  110. | { type: 'pop-in-done'; requestId: string }
  111. | { type: 'pop-in-refused'; requestId: string; instanceId: string };
  112. function randomId(prefix: string): string {
  113. // Math.random: crypto.randomUUID needs a secure context (see useCameraViewerId).
  114. return `${prefix}${Math.random().toString(36).slice(2, 12)}`;
  115. }
  116. /**
  117. * This tab's id, kept in sessionStorage so a popup it opens inherits it. It
  118. * survives a reload or a sign-in again, so a camera window opened before
  119. * still finds the tab it came from.
  120. */
  121. export function registerCameraTab(): string {
  122. try {
  123. const existing = sessionStorage.getItem(TAB_ID_KEY);
  124. if (existing) return existing;
  125. const tabId = randomId('t');
  126. sessionStorage.setItem(TAB_ID_KEY, tabId);
  127. return tabId;
  128. } catch {
  129. // Without it the window still pops in, just not necessarily to this tab.
  130. return randomId('t');
  131. }
  132. }
  133. /** The tab this camera window was opened from, if it was. */
  134. export function readOpenerTabId(): string | null {
  135. try {
  136. return sessionStorage.getItem(TAB_ID_KEY);
  137. } catch {
  138. return null;
  139. }
  140. }
  141. /**
  142. * Answer camera windows asking to move into a tab; `open` shows the overlay.
  143. * Returns the cleanup.
  144. *
  145. * A duplicated tab starts with a copy of sessionStorage and so the same tab
  146. * id; the claim names one listener (`instanceId`), so only one of them opens.
  147. * `canShow` is asked before saying done: each tab has its own sign-in, and a
  148. * tab whose user cannot see the printer would drop the overlay right after
  149. * the window had closed. It refuses instead, and the window asks the next.
  150. */
  151. export function listenForCameraPopIn(
  152. tabId: string,
  153. open: (printerId: number, printerName: string) => void,
  154. canShow: (printerId: number) => Promise<boolean> = async () => true,
  155. ): () => void {
  156. if (typeof BroadcastChannel === 'undefined') return () => {};
  157. const channel = new BroadcastChannel(CAMERA_CHANNEL);
  158. let closed = false;
  159. const instanceId = randomId('i');
  160. const offers = new Map<string, { printerId: number; printerName: string }>();
  161. channel.onmessage = async (event: MessageEvent<PopInMessage>) => {
  162. const msg = event.data;
  163. if (msg?.type === 'pop-in-offer' && Number.isInteger(msg.printerId) && msg.printerId > 0) {
  164. offers.set(msg.requestId, { printerId: msg.printerId, printerName: String(msg.printerName ?? '') });
  165. channel.postMessage({ type: 'pop-in-candidate', requestId: msg.requestId, tabId, instanceId } satisfies PopInMessage);
  166. } else if (msg?.type === 'pop-in-claim') {
  167. if (msg.instanceId !== instanceId) return;
  168. const offer = offers.get(msg.requestId);
  169. offers.delete(msg.requestId);
  170. if (!offer) return;
  171. let allowed = false;
  172. try {
  173. allowed = await canShow(offer.printerId);
  174. } catch {
  175. allowed = false;
  176. }
  177. if (closed) return;
  178. if (!allowed) {
  179. channel.postMessage({ type: 'pop-in-refused', requestId: msg.requestId, instanceId } satisfies PopInMessage);
  180. return;
  181. }
  182. // A claim that reaches a throttled background tab after the window
  183. // gave up would show the camera twice: the window kept its own.
  184. if (!(Date.now() <= msg.deadline)) return;
  185. open(offer.printerId, offer.printerName);
  186. channel.postMessage({ type: 'pop-in-done', requestId: msg.requestId } satisfies PopInMessage);
  187. } else if (msg?.type === 'pop-in-done') {
  188. // Another tab took it; an offer this one was not claimed for is over.
  189. offers.delete(msg.requestId);
  190. }
  191. };
  192. return () => {
  193. closed = true;
  194. channel.close();
  195. };
  196. }
  197. /**
  198. * Ask a Bambuddy tab to take this camera as an overlay. Resolves true once one
  199. * has opened it, false when no tab answered (none open, or all signed out),
  200. * none could show the printer, or the claimed one did not open it in time.
  201. */
  202. export function requestCameraPopIn(
  203. printerId: number,
  204. printerName: string,
  205. preferredTabId: string | null,
  206. { answerMs = 400, doneMs = 3000 }: { answerMs?: number; doneMs?: number } = {},
  207. ): Promise<boolean> {
  208. if (typeof BroadcastChannel === 'undefined') return Promise.resolve(false);
  209. const channel = new BroadcastChannel(CAMERA_CHANNEL);
  210. const requestId = randomId('r');
  211. return new Promise<boolean>((resolve) => {
  212. const candidates: Array<{ tabId: string; instanceId: string }> = [];
  213. let claimedId: string | null = null;
  214. let timer: ReturnType<typeof setTimeout>;
  215. const finish = (ok: boolean) => {
  216. clearTimeout(timer);
  217. channel.close();
  218. resolve(ok);
  219. };
  220. const claimNext = () => {
  221. clearTimeout(timer);
  222. const target = candidates.find(c => c.tabId === preferredTabId) ?? candidates[0];
  223. if (!target) {
  224. finish(false);
  225. return;
  226. }
  227. candidates.splice(candidates.indexOf(target), 1);
  228. claimedId = target.instanceId;
  229. // The tab must open it before this window stops waiting; a margin
  230. // covers the done message's own trip back.
  231. const deadline = Date.now() + doneMs / 2;
  232. channel.postMessage({ type: 'pop-in-claim', requestId, instanceId: target.instanceId, deadline } satisfies PopInMessage);
  233. timer = setTimeout(() => finish(false), doneMs);
  234. };
  235. channel.onmessage = (event: MessageEvent<PopInMessage>) => {
  236. const msg = event.data;
  237. if (msg?.requestId !== requestId) return;
  238. if (msg.type === 'pop-in-candidate') {
  239. // Kept after a claim too: a tab that refuses hands on to the others.
  240. candidates.push({ tabId: msg.tabId, instanceId: msg.instanceId });
  241. // The tab it came from needs no waiting for the others.
  242. if (claimedId === null && preferredTabId && msg.tabId === preferredTabId) claimNext();
  243. } else if (msg.type === 'pop-in-refused' && msg.instanceId === claimedId) {
  244. claimNext();
  245. } else if (msg.type === 'pop-in-done') {
  246. finish(true);
  247. }
  248. };
  249. timer = setTimeout(claimNext, answerMs);
  250. channel.postMessage({ type: 'pop-in-offer', requestId, printerId, printerName } satisfies PopInMessage);
  251. });
  252. }