|
| 1 | +import React, { useCallback, useState } from "react"; |
| 2 | +import Api, { GetSessionResponse, KioskControlReload } from "./Api"; |
| 3 | +import { useChat } from "./ChatProvider"; |
| 4 | +import { ChatUpdate } from "./ChatSession"; |
| 5 | +import { COMMIT } from "./meta"; |
| 6 | + |
| 7 | +const respondPing = async (hb: number) => { |
| 8 | + try { |
| 9 | + await Api.updateKioskHeartbeat({ last_heartbeat_at: hb, version: COMMIT }); |
| 10 | + } catch (e) { |
| 11 | + console.warn(e); |
| 12 | + } |
| 13 | +}; |
| 14 | + |
| 15 | +const handleReload = async (session: GetSessionResponse, reload: KioskControlReload) => { |
| 16 | + if (session?.kiosk === reload.name || reload.all) { |
| 17 | + location.reload(); |
| 18 | + } |
| 19 | +}; |
| 20 | + |
| 21 | +export const KioskHeartbeat: React.FC = () => { |
| 22 | + const { data: session } = Api.useSession(); |
| 23 | + const chat = useChat(); |
| 24 | + const [_lastHeartbeat, setLastHeartbeat] = useState(-1); |
| 25 | + const systemsChannel = chat.systems_channel_arn; |
| 26 | + |
| 27 | + const onMessage = useCallback( |
| 28 | + (update: ChatUpdate) => { |
| 29 | + if (!session) return null; |
| 30 | + if (!session.kiosk) return null; |
| 31 | + |
| 32 | + console.log("KioskHeartbeat: onMessage", update); |
| 33 | + const kioskControl = update.message?.adminControl?.kiosk_control; |
| 34 | + if (!kioskControl) return; |
| 35 | + |
| 36 | + if (kioskControl.reload) handleReload(session, kioskControl.reload); |
| 37 | + |
| 38 | + if (kioskControl.ping) { |
| 39 | + const t = kioskControl.ping; |
| 40 | + setLastHeartbeat(t); |
| 41 | + setTimeout(() => respondPing(t), Math.floor(Math.random() * 15000)); |
| 42 | + } |
| 43 | + }, |
| 44 | + [session], |
| 45 | + ); |
| 46 | + |
| 47 | + React.useEffect(() => { |
| 48 | + if (!session) return; |
| 49 | + if (!session.kiosk) return; |
| 50 | + if (!chat.session) return; |
| 51 | + if (!systemsChannel) return; |
| 52 | + |
| 53 | + console.log("KioskHeartbeat: subscribeMessageUpdate"); |
| 54 | + |
| 55 | + const unsubscribe = chat.session.subscribeMessageUpdate(systemsChannel, onMessage); |
| 56 | + |
| 57 | + return () => { |
| 58 | + console.log("KioskHeartbeat: subscribeMessageUpdate; unsubscribing"); |
| 59 | + unsubscribe(); |
| 60 | + }; |
| 61 | + }, [chat.session, systemsChannel, onMessage]); |
| 62 | + |
| 63 | + if (!session) return null; |
| 64 | + if (!session.kiosk) return null; |
| 65 | + |
| 66 | + return null; |
| 67 | +}; |
0 commit comments