import "pkg:/components/parts/AutoBind/OnNodeReadyNoOp.bs" import "pkg:/components/Services/LoungeService/LoungeApi.bs" function Init() m.top.functionName = "LoungeServiceLoop" deviceInfo = CreateObject("roDeviceInfo") m.top.deviceId = deviceInfo.GetRandomUUID() deviceFriendlyName = deviceInfo.GetFriendlyName() if StringUtils.IsNullOrEmpty(deviceFriendlyName) deviceFriendlyName = "TV" end if m.top.deviceName = "Playlet on " + deviceFriendlyName end function function StartService(_unused as dynamic) as boolean if m.top.isRunning = true return true end if m.top.control = "run" return true end function function StopService(_unused as dynamic) as void if m.top.isRunning = false return end if m.top.shouldQuit = true end function function LoungeServiceLoop() as void api = new LoungeApi(m.top, m.top.videoQueue, m.top.notifications, m.top.invidious) ' Mobile app can remain connected to devices even after restarts. ' Since we create a new lounge every time, we signal to the last lounge ' that we're no longer there, and we're not coming back. api.DisconnectFromLastLounge() messagePort = CreateObject("roMessagePort") ' We do not join a lounge until something asks us to like ' - A remote connects through DIAL ' - Generating a TV link code m.top.observeField("join", messagePort) wait(0, messagePort) m.top.unobserveField("join") screenId = api.GetScreenId() if StringUtils.IsNullOrEmpty(screenId) Shutdown("No screen ID found") return end if m.top.screenId = screenId loungeToken = api.GetToken() if StringUtils.IsNullOrEmpty(loungeToken) Shutdown("No lounge token found") return end if m.top.loungeToken = loungeToken m.top.observeField("outgoingMessages", messagePort) if not api.GetSessionData() Shutdown("Failed to get session data") return end if api.SaveCurrentLoungeData() api.FetchCommandsRpc(messagePort) m.top.shouldQuit = false isOpen = false reconnectAttempts = 0 outgoingLoungeMessages = [] portMessages = [] socketMessages = [] while true if m.top.shouldQuit = true exit while end if message = wait(60000, messagePort) portMessages.Clear() portMessages.Push(message) ' There's a chance messages were piling up while we were sending messages to the lounge ' This could happen if we were sending things to the lounge and the player state ' changed many times. while messagePort.PeekMessage() <> invalid portMessages.Push(messagePort.GetMessage()) end while ' At this point: ' - We check if we need to send messages to the lounge based on player state ' - We check the lounge for new commands, which might need responding to ' - Finally, we send the outgoing messages to the lounge in one go outgoingLoungeMessages.Clear() socketMessages.Clear() for each portMessage in portMessages messageType = type(portMessage) if messageType = "roSocketEvent" socketMessages.Push(portMessage) else if messageType = "roSGNodeEvent" field = portMessage.GetField() if field = "outgoingMessages" messages = portMessage.GetData() outgoingLoungeMessages.Append(messages) end if end if end for isOpen = api.Poll(socketMessages, outgoingLoungeMessages) api.SendMessages(outgoingLoungeMessages) outgoingLoungeMessagesResults = api.ProcessPendingOutgoingMessages() if not isOpen closeInfo = api.GetCloseInfo() needsRebind = closeInfo.statusCode = 410 or closeInfo.statusCode = 400 needsTokenRefresh = closeInfo.statusCode = 401 for each result in outgoingLoungeMessagesResults if result.status = 410 or (result.status = 400 and result.error.InStr("Unknown SID") <> -1) needsRebind = true else if result.status = 401 and result.error.InStr("Expired lounge id token") <> -1 needsTokenRefresh = true end if end for LogDebug("Backchannel closed:", closeInfo.reason) if IsActionableCloseFailure(closeInfo.reason, needsRebind, needsTokenRefresh) message = "Lounge backchannel failure: " + closeInfo.reason if not StringUtils.IsNullOrEmpty(closeInfo.target) message += " -> " + closeInfo.target end if LogTelemetryEvent({ level: "warning" message: message fingerprint: "lounge-backchannel-" + closeInfo.reason }) end if sleep(ComputeReconnectBackoffMs(reconnectAttempts)) reconnectAttempts += 1 if needsTokenRefresh LogWarnNoTelemetry("Lounge token expired, refreshing") api.RefreshToken() needsRebind = true end if if needsRebind LogWarnNoTelemetry("Rejoining lounge session") if not api.GetSessionData() Shutdown("Failed to rejoin session data") return end if api.SaveCurrentLoungeData() end if api.FetchCommandsRpc(messagePort) else reconnectAttempts = 0 end if end while Shutdown("Service stopped") end function function Shutdown(reason as string) LogInfo("Shutting down:", reason) m.top.unobserveField("outgoingMessages") m.top.isRunning = false end function ' Full jitter (random in [0, window)) avoids a fleet-wide thundering-herd reconnect. function ComputeReconnectBackoffMs(attempts as integer) as integer capped = attempts if capped > 6 capped = 6 end if windowMs = 1000 * (2 ^ capped) if windowMs > 30000 windowMs = 30000 end if return 500 + Int(Rnd(0) * windowMs) end function function IsActionableCloseFailure(reason as string, needsRebind as boolean, needsTokenRefresh as boolean) as boolean if needsRebind or needsTokenRefresh return false end if if reason = "complete" or reason = "eof" or reason = "closed" or reason = "timeout" or reason = "disconnected" or reason = "" return false end if return true end function