Cast using Youtube app (DIAL/LoungeAPI) (#276)

* Dial+Lounge API PoC

* format

* Fix for chrome

* comments

* Rate limit and logger stuff

* rename route

* remove invalid routes

* remove device image

* Simplify device description

* command test

* Lint fix

* register pairing code

* tv code UI

* Lint fix

* Avoid creating lots of objects

* dpad command

* small refactor

* tweak

* validation

* timer

* fix

* Revert "timer"

This reverts commit e349565910882408898c9bddda55dadaa9d743de.

* Commands

* setVolume command

* lounge service timer

* Some state messages

* Lint fix

* player state sync

* voice handler

* Adjustments, and add a TODO list

* Lint fix

* comment

* play at timestamp

* Remote screen UI

* UI adjustment

* Small refactor

* Refactor long polling

* Add TODO

* Manage logging a bit better to avoid spam in DIAL server

* cache dial file

* logging

* comment

* Join lounge lazily

* long poller tweak

* ui tweak

* set shouldQuit field

* remote connect notification

* Lint fix

* Randomize device id, new device on start

* Lint fix

* Lounge disconnect on start

* Speed up lounge by not blocking on sent messages

* add version to lounge data saved

* dial server fix rendezvous

* todo

* no message

* Display network name

* playlist changes

* Lint fix

* tweak params

* tweak

* player state

* comments

* Refactor Video Queue (#295)

* Refactor Video Queue

* Video queue and playlists

* Web app casting

* queue playlist notification

* VideoQueueView work

* restore properties

* changes

* queue notification and previous/next state

* Lint fix

* very basic error handling

* Update changelog and privacy policy

---------

Co-authored-by: github-action linter <githubaction@githubaction.com>
This commit is contained in:
Brahim Hadricheandgithub-action linter authored and GitHub committed 2024-02-19 16:30:48 -05:00
1 parent ec9178d687
commit 7d1ba07286
85 files changed
+3666 -938

No files matched your search

@@ -41,26 +41,16 @@ namespace Invidious
function new(node as object)
m.node = node
m.endpoints = node.apiDefinitions
m.responseHandlers = {
DefaultHandler: m.DefaultHandler
AuthFeedHandler: m.AuthFeedHandler
PlaylistHandler: m.PlaylistHandler
VideoInfoHandler: m.VideoInfoHandler
PlaylistInfoHandler: m.PlaylistInfoHandler
ChannelInfoHandler: m.ChannelInfoHandler
ChannelVideosHandler: m.ChannelVideosHandler
ChannelPlaylistsHandler: m.ChannelPlaylistsHandler
WatchHistoryHandler: m.WatchHistoryHandler
}
end function
function DefaultQueryParams() as object
return {
region: m.node.applicationInfo@.GetUserCountryCode()
}
if m._defaultQueryParams = invalid
m._defaultQueryParams = {
"region": m.node.applicationInfo@.GetUserCountryCode()
}
end if
return m._defaultQueryParams
end function
function GetAuthenticationHeaders(token as string) as object
@@ -187,6 +177,10 @@ namespace Invidious
feedSource = feedSources[feedSourcesIndex]
if m.endpoints = invalid
m.endpoints = m.node.apiDefinitions
end if
endpoint = m.endpoints[feedSource.endpoint]
if endpoint = invalid or StringUtils.IsNullOrEmpty(endpoint.paginationType)
return feedSource
@@ -220,6 +214,10 @@ namespace Invidious
end function
function MakeRequest(feedSource as object, additionalQueryParams = invalid as object, cancellation = invalid as object) as object
if m.endpoints = invalid
m.endpoints = m.node.apiDefinitions
end if
endpoint = m.endpoints[feedSource.endpoint]
if endpoint = invalid
return {
@@ -291,6 +289,20 @@ namespace Invidious
response = request.Await()
if m.responseHandlers = invalid
m.responseHandlers = {
DefaultHandler: m.DefaultHandler
AuthFeedHandler: m.AuthFeedHandler
PlaylistHandler: m.PlaylistHandler
VideoInfoHandler: m.VideoInfoHandler
PlaylistInfoHandler: m.PlaylistInfoHandler
ChannelInfoHandler: m.ChannelInfoHandler
ChannelVideosHandler: m.ChannelVideosHandler
ChannelPlaylistsHandler: m.ChannelPlaylistsHandler
WatchHistoryHandler: m.WatchHistoryHandler
}
end if
responseHandler = endpoint.responseHandler <> invalid ? m.responseHandlers[endpoint.responseHandler] : m.responseHandlers["DefaultHandler"]
result = responseHandler(m, feedSource, response)
@@ -1,4 +1,5 @@
import "pkg:/components/VideoFeed/FeedLoadState.bs"
import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/TimeUtils.bs"
namespace InvidiousContent
@@ -33,7 +34,8 @@ namespace InvidiousContent
end if
node.type = "video"
SetIfExists(node, "author", item, "author")
' NOTE: "_author" not "author". See PlaylistContentNode.xml for explanation.
SetIfExists(node, "_author", item, "author")
SetIfExists(node, "authorId", item, "authorId")
SetIfExists(node, "lengthSeconds", item, "lengthSeconds")
node.lengthText = TimeUtils.GetFormattedTime(item.lengthSeconds)
@@ -43,6 +45,7 @@ namespace InvidiousContent
VideoSetThumbnail(node, item, instance)
SetIfExists(node, "title", item, "title")
SetIfExists(node, "timestamp", item, "timestamp")
SetIfExists(node, "id", item, "videoId")
SetIfExists(node, "videoId", item, "videoId")
node.viewCountText = VideoGetViewCountText(item)
SetIfExists(node, "index", item, "index")
@@ -61,6 +64,7 @@ namespace InvidiousContent
SetIfExists(node, "_author", item, "author")
SetIfExists(node, "authorId", item, "authorId")
SetIfExists(node, "description", item, "description")
SetIfExists(node, "id", item, "playlistId")
SetIfExists(node, "playlistId", item, "playlistId")
SetIfExists(node, "title", item, "title")
SetIfExists(node, "videoCount", item, "videoCount")
@@ -105,6 +109,7 @@ namespace InvidiousContent
' NOTE: "_author" not "author". See PlaylistContentNode.xml for explanation.
SetIfExists(node, "_author", item, "author")
SetIfExists(node, "id", item, "authorId")
SetIfExists(node, "authorId", item, "authorId")
SetIfExists(node, "channelHandle", item, "channelHandle")
SetIfExists(node, "description", item, "description")
@@ -0,0 +1,298 @@
import "pkg:/source/utils/Logging.bs"
import "pkg:/source/utils/UrlUtils.bs"
const LONG_POLL_BUFSIZE = 65536
const LONG_POLL_TIMEOUT_MS = 60000
enum HttpResponseState
INIT = 0
READING_STATUS = 1
READING_HEADERS = 2
READING_BODY_CHUNK_SIZE = 3
READING_BODY_CHUNK = 4
end enum
class LongPoller
' Socket stuff for long polling
private socket
private socket_buffer
private socket_state = HttpResponseState.INIT
private socket_chunk_size = 0
private socket_timer
private status_code = 0
private headers
function new()
m.socket_timer = CreateObject("roTimespan")
end function
function SendRequest(url as string, messagePort as object) as boolean
m.url = url
urlObject = UrlUtils.ParseUrl(url)
if urlObject.protocol <> "http"
throw `Invalid protocol: ${urlObject.protocol}`
end if
sendAddress = CreateObject("roSocketAddress")
sendAddress.SetAddress(`${urlObject.host}:${urlObject.port}`)
socket = CreateObject("roStreamSocket")
socket.setSendToAddress(sendAddress)
if not socket.Connect()
LogError("Failed to connect")
return false
end if
LogInfo(`Sending long polling GET ${url}`, "ID:", socket.GetID())
#if DEBUG
? `════════ curl command ════════\n${m.ToCurlCommand()}\n══════════════════════════════`
#end if
message = `GET ${urlObject.path} HTTP/1.1\r\n`
message += `Host: ${urlObject.host}\r\n`
message += `\r\n`
socket.SendStr(message)
socket.notifyReadable(true)
socket.setMessagePort(messagePort)
m.socket = socket
m.socket_timer.Mark()
return true
end function
' Returns:
' - false if we're no longer returning data - socket is closed
' - true if we're still waiting for data
' - array we've received chunk(s) of data
function Poll(socketMessages as object) as dynamic
if m.socket = invalid
return false
end if
socket = m.socket
if not socket.IsConnected()
LogError("Socket is not connected")
m.CloseSocket()
return false
end if
' Not receiving data for LONG_POLL_TIMEOUT_MS seconds might be a sign of a dead connection
if m.socket_timer.TotalMilliseconds() > LONG_POLL_TIMEOUT_MS
LogWarn("Timeout after", LONG_POLL_TIMEOUT_MS, "ms")
m.CloseSocket()
return false
end if
if socketMessages.Count() = 0
return true
end if
hasDataToReceive = false
for each socketMessage in socketMessages
if socketMessage.GetSocketID() = socket.GetID()
hasDataToReceive = true
exit for
end if
end for
if not hasDataToReceive
return true
end if
data = socket.ReceiveStr(LONG_POLL_BUFSIZE)
if not socket.eSuccess()
LogError("Error receiving data")
m.CloseSocket()
return false
end if
m.socket_timer.Mark()
if m.socket_buffer = invalid
m.socket_buffer = ""
end if
m.socket_buffer += data
return m.ParseData()
end function
function IsOpen() as boolean
return m.socket <> invalid and m.socket.IsConnected()
end function
function CloseSocket() as void
if m.socket = invalid
return
end if
m.socket.notifyReadable(false)
m.socket.close()
m.socket = invalid
m.socket_buffer = invalid
m.socket_state = HttpResponseState.INIT
end function
function ParseData() as dynamic
if m.socket_state = HttpResponseState.INIT
m.socket_state = HttpResponseState.READING_STATUS
end if
if m.socket_state = HttpResponseState.READING_STATUS
if not m.ParseOpration()
return false
end if
end if
if m.socket_state = HttpResponseState.READING_HEADERS
if not m.ParseHeaders()
return false
end if
end if
chunks = []
READING_BODY_CHUNK_SIZE:
if m.socket_state = HttpResponseState.READING_BODY_CHUNK_SIZE
if not m.ParseChunkSize()
return chunks
end if
end if
if m.socket_state = HttpResponseState.READING_BODY_CHUNK
chunk = m.ParseChunk()
if IsBool(chunk)
if not chunk
return chunks
end if
else
chunks.Push(chunk)
goto READING_BODY_CHUNK_SIZE
end if
end if
return chunks
end function
function ParseOpration() as boolean
newLineIndex = m.socket_buffer.InStr(`\r\n`)
if newLineIndex > 0
operationLine = m.socket_buffer.Left(newLineIndex)
parts = operationLine.Split(" ")
if parts.Count() <> 3 or parts[0] <> "HTTP/1.1"
LogError("Invalid operation line:", operationLine)
m.CloseSocket()
return false
end if
m.status_code = Val(parts[1])
if not m.status_code = 200
LogError("Http status code:", m.status_code)
LogError("Response data:", m.socket_buffer)
m.CloseSocket()
return false
end if
m.socket_buffer = m.socket_buffer.Mid(newLineIndex + 2)
m.socket_state = HttpResponseState.READING_HEADERS
end if
return true
end function
function ParseHeaders() as boolean
newLineIndex = m.socket_buffer.InStr(`\r\n\r\n`)
if newLineIndex > 0
headersStr = m.socket_buffer.Left(newLineIndex)
headers = {}
headerLines = headersStr.Split(`\r\n`)
for each headerLine in headerLines
colonIndex = headerLine.InStr(":")
key = headerLine.Left(colonIndex).Trim()
value = headerLine.Mid(colonIndex + 1).Trim()
headers[key] = value
end for
m.headers = headers
LogDebug("Headers:", headers)
if headers["Transfer-Encoding"] <> "chunked"
LogError("Invalid transfer encoding:", headers["Transfer-Encoding"])
m.CloseSocket()
return false
end if
m.socket_buffer = m.socket_buffer.Mid(newLineIndex + 4)
m.socket_state = HttpResponseState.READING_BODY_CHUNK_SIZE
end if
return true
end function
function ParseChunkSize() as boolean
m.ConsumeNewLines()
newLineIndex = m.socket_buffer.InStr(`\r\n`)
if newLineIndex > 0
chunkSize = m.socket_buffer.Left(newLineIndex)
chunkSize = chunkSize.Trim()
chunkSize = Val(chunkSize, 16)
LogDebug("Chunk size:", chunkSize)
m.socket_chunk_size = chunkSize
if chunkSize = 0
LogDebug("End of chunked data")
m.CloseSocket()
return false
end if
m.socket_buffer = m.socket_buffer.Mid(newLineIndex + 2)
m.socket_state = HttpResponseState.READING_BODY_CHUNK
end if
return true
end function
function ParseChunk() as dynamic
if m.socket_chunk_size > 0
if m.socket_buffer.Len() >= m.socket_chunk_size
chunk = m.socket_buffer.Left(m.socket_chunk_size)
m.socket_buffer = m.socket_buffer.Mid(m.socket_chunk_size)
m.socket_chunk_size = 0
m.socket_state = HttpResponseState.READING_BODY_CHUNK_SIZE
return chunk
end if
else
LogError("Invalid chunk size")
m.CloseSocket()
return false
end if
return true
end function
function ConsumeNewLines()
CR = `\r`
LF = `\n`
startIndex = 0
while true
char = m.socket_buffer.Mid(startIndex, 1)
if char = CR or char = LF
startIndex += 1
else
exit while
end if
end while
if startIndex > 0
m.socket_buffer = m.socket_buffer.Mid(startIndex)
end if
end function
function ToCurlCommand() as string
' It won't work the same since it will disconnect quickly
return `curl "${m.url}"`
end function
end class
@@ -0,0 +1,573 @@
import "pkg:/components/Dialog/DialogUtils.bs"
import "pkg:/components/Services/Invidious/InvidiousToContentNode.bs"
import "pkg:/components/Services/LoungeService/LongPoller.bs"
import "pkg:/components/Services/LoungeService/LoungeConstants.bs"
import "pkg:/components/Services/LoungeService/LoungeMessages.bs"
import "pkg:/components/Services/LoungeService/LoungeVideoQueue.bs"
import "pkg:/components/Services/LoungeService/Notifications/DeviceConnectedNotificationUtils.bs"
import "pkg:/source/services/HttpClient.bs"
import "pkg:/source/utils/Logging.bs"
import "pkg:/source/utils/RegistryUtils.bs"
import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/UrlUtils.bs"
const COMMAND_HANDLER_PREFIX = "_Handle_"
class LoungeApi
public loungeServiceNode
public videoQueueNode
public notificationsNode
public invService
public deviceId
public deviceName
public screenId
public screenName
public loungeToken
public sessionId
public gSessionId
private ofs
private lastProcessedCommandIndex = -1
private poller
private outgoingMessagesRequests
function new(loungeServiceNode as object, videoQueueNode as object, notificationsNode as object, invidiousNode as object)
m.loungeServiceNode = loungeServiceNode
m.videoQueueNode = videoQueueNode
m.notificationsNode = notificationsNode
m.invService = new Invidious.InvidiousService(invidiousNode)
m.deviceId = loungeServiceNode.deviceId
deviceName = loungeServiceNode.deviceName
m.deviceName = deviceName
m.screenName = deviceName
m.ofs = 0
m.poller = invalid
m.outgoingMessagesRequests = {}
commandHandlers = {}
commandHandlers[COMMAND_TYPE_NOOP] = m.HandleIgnoreCommand
commandHandlers[COMMAND_TYPE_GET_VOLUME] = m.HandleIgnoreCommand
commandHandlers[COMMAND_TYPE_GET_SUBTITLES_TRACK] = m.HandleIgnoreCommand
commandHandlers[COMMAND_TYPE_SET_SUBTITLES] = m.HandleIgnoreCommand
commandHandlers[COMMAND_TYPE_DPAD_COMMAND] = m.HandleIgnoreCommand
commandHandlers[COMMAND_TYPE_VOICE_COMMAND] = m.HandleIgnoreCommand
commandHandlers[COMMAND_TYPE_ON_USER_ACTIVITY] = m.HandleIgnoreCommand
commandHandlers[COMMAND_TYPE_GET_NOW_PLAYING] = m.HandleGetPlayingNow
commandHandlers[COMMAND_TYPE_SESSION_ID] = m.HandleSessionId
commandHandlers[COMMAND_TYPE_G_SESSION_ID] = m.HandleGSessionId
commandHandlers[COMMAND_TYPE_LOUNGE_STATUS] = m.HandleLoungeStatus
commandHandlers[COMMAND_TYPE_REMOTE_CONNECTED] = m.HandleRemoteConnected
commandHandlers[COMMAND_TYPE_REMOTE_DISCONNECTED] = m.HandleRemoteDisconnected
commandHandlers[COMMAND_TYPE_SET_VOLUME] = m.HandleSetVolume
commandHandlers[COMMAND_TYPE_SET_PLAYLIST] = m.HandleSetPlaylist
commandHandlers[COMMAND_TYPE_UPDATE_PLAYLIST] = m.HandleUpdatePlaylist
commandHandlers[COMMAND_TYPE_PAUSE] = m.HandlePause
commandHandlers[COMMAND_TYPE_PLAY] = m.HandlePlay
commandHandlers[COMMAND_TYPE_STOP_VIDEO] = m.HandleStopVideo
commandHandlers[COMMAND_TYPE_SEEK_TO] = m.HandleSeekTo
for each key in commandHandlers
m[COMMAND_HANDLER_PREFIX + key] = commandHandlers[key]
end for
end function
function GetScreenId() as dynamic
if not StringUtils.IsNullOrEmpty(m.screenId)
return m.screenId
end if
request = HttpClient.Get("https://www.youtube.com/api/lounge/pairing/generate_screen_id")
response = request.Await()
if not response.IsSuccess()
error = `Failed to get screen id. Please restart playlet to use the cast function.\n${response.ErrorMessage()}`
LogError(error)
DialogUtils.ShowDialog(error, "Lounge service setup error")
return invalid
end if
id = response.Text()
if not IsString(id)
error = `Failed to get screen id. Please restart playlet to use the cast function.\nNot a valid screen id: ${id}`
LogError(error)
DialogUtils.ShowDialog(error, "Lounge service setup error")
return invalid
end if
m.screenId = id
return id
end function
function GetToken() as dynamic
if not StringUtils.IsNullOrEmpty(m.loungeToken)
return m.loungeToken
end if
form = UrlUtils.GetUrlEncodedForm({ "screen_ids": m.screenId })
request = HttpClient.Post("https://www.youtube.com/api/lounge/pairing/get_lounge_token_batch", form)
request.Header("Content-Type", "application/x-www-form-urlencoded")
response = request.Await()
if not response.IsSuccess()
error = `Failed to get lounge token. Please restart playlet to use the cast function.\n${response.ErrorMessage()}`
LogError(error)
DialogUtils.ShowDialog(error, "Lounge service setup error")
return invalid
end if
json = response.Json()
screens = json.screens
if not IsArray(screens) or screens.Count() <> 1
error = `Failed to get lounge token. Please restart playlet to use the cast function.\nInvalid response: ${json}`
LogError(error)
DialogUtils.ShowDialog(error, "Lounge service setup error")
return invalid
end if
' payload contains more information, but we only need the token
m.loungeToken = screens[0].loungeToken
return m.loungeToken
end function
function GetSessionData() as boolean
baseUrl = "https://www.youtube.com/api/lounge/bc/bind"
queryParams = {
"device": "LOUNGE_SCREEN"
"theme": "cl"
"capabilities": ""
"mdxVersion": "2"
"VER": "8"
"v": "2"
"t": "1"
"zx": "xxxxxxxxxxxx"
"app": "lb-v4"
"RID": "1337"
}
queryParams["name"] = m.screenName
queryParams["id"] = m.deviceId
queryParams["loungeIdToken"] = m.loungeToken
url = UrlUtils.BuildUrl(baseUrl, invalid, queryParams)
request = HttpClient.Post(url, "count=0")
request.Header("Content-Type", "application/x-www-form-urlencoded")
response = request.Await()
if not response.IsSuccess()
error = `Failed to get session data. Please restart playlet to use the cast function.\n${response.ErrorMessage()}`
LogError(error)
DialogUtils.ShowDialog(error, "Lounge service setup error")
return false
end if
text = response.Text()
' First line should be a number, which is the length of the JSON payload
text = text.Mid(text.instr(`\n`) + 1)
messagesToSend = []
commands = ParseJson(text)
m.ProcessCommands(commands, messagesToSend)
m.SendMessages(messagesToSend)
return true
end function
function FetchCommandsRpc(messagePort as object) as void
' Note we're not using https, not supported by LongPoller
baseUrl = "http://www.youtube.com/api/lounge/bc/bind"
queryParams = {
"device": "LOUNGE_SCREEN"
"theme": "cl"
"capabilities": ""
"mdxVersion": "2"
"VER": "8"
"v": "2"
"t": "1"
"zx": "xxxxxxxxxxxx"
"app": "lb-v4"
"RID": "rpc"
"CI": "0"
}
queryParams["name"] = m.screenName
queryParams["id"] = m.deviceId
queryParams["loungeIdToken"] = m.loungeToken
queryParams["SID"] = m.sessionId
queryParams["gsessionid"] = m.gSessionId
url = UrlUtils.BuildUrl(baseUrl, invalid, queryParams)
if m.poller = invalid
m.poller = new LongPoller()
end if
m.poller.SendRequest(url, messagePort)
end function
function Poll(socketMessages as object, messagesToSend as object) as boolean
chunks = m.poller.Poll(socketMessages)
if IsArray(chunks)
for each chunk in chunks
m.ProcessChunk(chunk, messagesToSend)
end for
end if
return m.poller.IsOpen()
end function
function ProcessChunk(chunk as string, messagesToSend as object) as void
chunk = m.ConsumeNewLines(chunk)
newLineIndex = chunk.InStr(`\n`)
while newLineIndex > 0
payloadSize = chunk.Left(newLineIndex).trim()
payloadSize = payloadSize.ToInt()
payload = chunk.Mid(newLineIndex + 1, payloadSize)
commands = ParseJson(payload)
m.ProcessCommands(commands, messagesToSend)
chunk = chunk.Mid(newLineIndex + payloadSize + 1)
newLineIndex = chunk.InStr(`\n`)
end while
end function
function ConsumeNewLines(chunk as string) as string
CR = `\r`
LF = `\n`
startIndex = 0
while true
char = chunk.Mid(startIndex, 1)
if char = CR or char = LF
startIndex += 1
else
exit while
end if
end while
if startIndex > 0
return chunk.Mid(startIndex)
end if
return chunk
end function
function ProcessCommands(commands as object, messagesToSend as object) as void
if not IsArray(commands)
return
end if
for each command in commands
if not IsArray(command) or command.Count() <> 2
continue for
end if
commandIndex = command[0]
if commandIndex <= m.lastProcessedCommandIndex
LogDebug("Skipping command already processed:", command)
continue for
end if
m.lastProcessedCommandIndex = commandIndex
commandId = command[0]
commandData = command[1]
commandType = commandData[0]
commandArgs = invalid
if commandData.Count() > 1
commandArgs = commandData[1]
end if
handler = COMMAND_HANDLER_PREFIX + commandType
if m.DoesExist(handler)
LogInfo(commandType)
m[handler](commandId, commandType, commandArgs, messagesToSend)
else
LogWarn("Unknown command type:", commandType, "command:", command)
end if
end for
end function
function HandleIgnoreCommand(commandId as integer, commandType as string, commandArgs as object, messagesToSend as object)
LogDebug("Ignoring command:", commandType, "args:", commandArgs)
end function
function HandleSessionId(commandId as integer, commandType as string, commandArgs as object, messagesToSend as object)
m.sessionId = commandArgs
LogInfo("sessionId:", m.sessionId)
end function
function HandleGSessionId(commandId as integer, commandType as string, commandArgs as object, messagesToSend as object)
m.gSessionId = commandArgs
LogInfo("gSessionId:", m.gSessionId)
end function
function HandleGetPlayingNow(commandId as integer, commandType as string, commandArgs as object, messagesToSend as object) as void
player = m.videoQueueNode.player
message = LoungeMessages.OnHasPreviousNextChanged(m.videoQueueNode.hasPrevious, m.videoQueueNode.hasNext)
message["commandId"] = commandId
messagesToSend.Push(message)
message = LoungeMessages.NowPlaying(player)
message["commandId"] = commandId
messagesToSend.Push(message)
message = LoungeMessages.OnStateChange(player)
message["commandId"] = commandId
messagesToSend.Push(message)
end function
function HandleLoungeStatus(commandId as integer, commandType as string, commandArgs as object, messagesToSend as object) as void
LogInfo(commandType, FormatJson(commandArgs))
devices = commandArgs["devices"]
if not IsString(devices)
return
end if
devices = ParseJson(devices)
if devices = invalid
return
end if
devicesDict = {}
for each device in devices
devicesDict[device.id] = device
end for
m.loungeServiceNode.devices = devicesDict
end function
function HandleRemoteConnected(commandId as integer, commandType as string, commandArgs as object, messagesToSend as object) as void
LogInfo(commandType)
newDevice = commandArgs
id = newDevice.id
if StringUtils.IsNullOrEmpty(id)
return
end if
devices = m.loungeServiceNode.devices
if devices = invalid
devices = {}
end if
if devices.DoesExist(id)
device = devices[id]
device.Append(newDevice)
newDevice = device
end if
devices[id] = newDevice
m.loungeServiceNode.devices = devices
userName = newDevice.user
if StringUtils.IsNullOrEmpty(userName)
userName = newDevice.name
end if
userAvatarUri = newDevice.userAvatarUri
LoungeDeviceConnected.ShowNotifcation(m.notificationsNode, userName, userAvatarUri)
end function
function HandleRemoteDisconnected(commandId as integer, commandType as string, commandArgs as object, messagesToSend as object) as void
LogInfo(commandType)
device = commandArgs
id = device.id
if StringUtils.IsNullOrEmpty(id)
return
end if
devices = m.loungeServiceNode.devices
if devices = invalid
devices = {}
end if
if devices.Delete(id)
m.loungeServiceNode.devices = devices
end if
' TODO:P1 disconnect notification
end function
function HandleSetVolume(commandId as integer, commandType as string, commandArgs as object, messagesToSend as object) as void
player = m.videoQueueNode.player
if player = invalid
return
end if
volume = Val(commandArgs["volume"])
isMute = volume = 0
LogInfo("Setting volume is not supported:", volume, "but can mute:", isMute)
' TODO:P2 volume should be set to the lounge state.
' Also the state needs to be separate from the player, since SponsorBlock can mute sections.
player.mute = isMute
end function
function HandleSetPlaylist(commandId as integer, commandType as string, commandArgs as object, messagesToSend as object)
LogDebug(commandType, commandArgs)
LoungeVideoQueue.SetPlaylist(m.videoQueueNode, m.invService, commandArgs)
end function
function HandleUpdatePlaylist(commandId as integer, commandType as string, commandArgs as object, messagesToSend as object)
LogDebug(commandType, commandArgs)
LoungeVideoQueue.UpdatePlaylist(m.videoQueueNode, m.invService, commandArgs)
end function
function HandlePause(commandId as integer, commandType as string, commandArgs as object, messagesToSend as object)
m.videoQueueNode.pause = true
end function
function HandlePlay(commandId as integer, commandType as string, commandArgs as object, messagesToSend as object)
m.videoQueueNode.play = true
end function
function HandleStopVideo(commandId as integer, commandType as string, commandArgs as object, messagesToSend as object)
m.videoQueueNode.closePlayer = true
end function
function HandleSeekTo(commandId as integer, commandType as string, commandArgs as object, messagesToSend as object) as void
player = m.videoQueueNode.player
if player = invalid
return
end if
seekTo = Val(commandArgs[FIELD_NEW_TIME])
LogInfo("Seeking to:", seekTo)
player.seek = seekTo
end function
function SendMessages(messages as object, loungeData = invalid as object) as void
if messages.Count() = 0
return
end if
baseUrl = "https://www.youtube.com/api/lounge/bc/bind"
queryParams = {
"device": "LOUNGE_SCREEN"
"theme": "cl"
"capabilities": ""
"mdxVersion": "2"
"VER": "8"
"v": "2"
"t": "1"
"zx": "xxxxxxxxxxxx"
"app": "lb-v4"
"RID": "1337"
}
if loungeData = invalid
loungeData = m
end if
queryParams["name"] = loungeData.screenName
queryParams["id"] = loungeData.deviceId
queryParams["loungeIdToken"] = loungeData.loungeToken
queryParams["SID"] = loungeData.sessionId
queryParams["gsessionid"] = loungeData.gSessionId
if messages[0].commandId <> invalid
queryParams["AID"] = messages[0].commandId
end if
url = UrlUtils.BuildUrl(baseUrl, invalid, queryParams)
postData = [
{ key: "count", value: messages.Count() }
{ key: "ofs", value: loungeData.ofs }
]
loungeData.ofs += messages.Count()
for i = 0 to messages.Count() - 1
message = messages[i]
keyPrefix = `req${i}_`
postData.Push({ key: `${keyPrefix}${FIELD_COMMAND_NAME}`, value: message.commandType })
commandArgs = message.commandArgs
if commandArgs <> invalid
for each key in commandArgs
postData.Push({ key: `${keyPrefix}${key}`, value: commandArgs[key] })
end for
end if
end for
LogDebug("Sending messages:", postData)
body = UrlUtils.GetUrlEncodedForm(postData)
request = HttpClient.Post(url, body)
request.Header("Content-Type", "application/x-www-form-urlencoded")
request.Send()
' we do not need to wait for requests to finish, we check on them later
' to avoid blocking the thread.
' This is specific to sent lounge messages, since we're not waiting for a response.
requestId = request.urlTransfer.GetIdentity().ToStr()
m.outgoingMessagesRequests[requestId] = request
end function
function ProcessPendingOutgoingMessages()
for each key in m.outgoingMessagesRequests
request = m.outgoingMessagesRequests[key]
if request.IsCompleted()
response = request.Await()
if not response.IsSuccess()
LogError(response.ErrorMessage())
end if
m.outgoingMessagesRequests.Delete(key)
end if
end for
end function
function SaveCurrentLoungeData() as void
loungeData = {
"__version": 1
}
fields = ["screenName", "deviceId", "loungeToken", "sessionId", "gSessionId"]
for each field in fields
if StringUtils.IsNullOrEmpty(m[field])
LogWarn("Lounge data will not be saved. missing field:", field)
return
end if
loungeData[field] = m[field]
end for
loungeData = FormatJson(loungeData)
RegistryUtils.Write(RegistryUtils.LAST_LOUNGE_DATA, loungeData)
end function
function DisconnectFromLastLounge() as void
loungeData = RegistryUtils.Read(RegistryUtils.LAST_LOUNGE_DATA)
if loungeData = invalid
return
end if
RegistryUtils.Delete(RegistryUtils.LAST_LOUNGE_DATA)
loungeData = ParseJson(loungeData)
if not IsAssociativeArray(loungeData)
LogWarn("Can't disconnect from lounge. Invalid data:", loungeData)
return
end if
if ValidInt(loungeData.__version) <> 1
LogWarn("Can't disconnect from lounge. Unknown version:", loungeData.__version)
return
end if
fields = ["screenName", "deviceId", "loungeToken", "sessionId", "gSessionId"]
for each field in fields
if StringUtils.IsNullOrEmpty(loungeData[field])
LogWarn("Can't disconnect from lounge. Missing field:", field)
return
end if
end for
messages = [{
"commandType": COMMAND_LOUNGE_SCREEN_DISCONNECTED
}]
LogInfo("Disconnecting from last lounge")
' Every time we send messages, we need to increment the ofs.
' This is so that the server recognizes old messages and doesn't process them.
' But we're currently disconnecting from a previous session, and since
' we didn't keep track of the ofs, so we'll just set it to a large number.
' This is the last message we'll be sending to this lounge.
loungeData.ofs = 99999999
m.SendMessages(messages, loungeData)
end function
end class
@@ -0,0 +1,73 @@
' Outgoing commands
const COMMAND_NOW_PLAYING = "nowPlaying"
const COMMAND_ON_STATE_CHANGE = "onStateChange"
const COMMAND_ON_VOLUME_CHANGED = "onVolumeChanged"
const COMMAND_ON_PREVIOUS_NEXT_CHANGE = "onHasPreviousNextChanged"
const COMMAND_LOUNGE_SCREEN_DISCONNECTED = "loungeScreenDisconnected"
' Incoming commands
const COMMAND_TYPE_SET_PLAYLIST = "setPlaylist"
const COMMAND_TYPE_LOUNGE_STATUS = "loungeStatus"
const COMMAND_TYPE_REMOTE_CONNECTED = "remoteConnected"
const COMMAND_TYPE_REMOTE_DISCONNECTED = "remoteDisconnected"
const COMMAND_TYPE_GET_NOW_PLAYING = "getNowPlaying"
const COMMAND_TYPE_GET_VOLUME = "getVolume"
const COMMAND_TYPE_GET_SUBTITLES_TRACK = "getSubtitlesTrack"
const COMMAND_TYPE_UPDATE_PLAYLIST = "updatePlaylist"
const COMMAND_TYPE_NOOP = "noop"
const COMMAND_TYPE_PLAY = "play"
const COMMAND_TYPE_PAUSE = "pause"
const COMMAND_TYPE_NEXT = "next"
const COMMAND_TYPE_PREVIOUS = "previous"
const COMMAND_TYPE_SEEK_TO = "seekTo"
const COMMAND_TYPE_SET_VOLUME = "setVolume"
const COMMAND_TYPE_STOP_VIDEO = "stopVideo"
const COMMAND_TYPE_DPAD_COMMAND = "dpadCommand"
const COMMAND_TYPE_VOICE_COMMAND = "voiceCommand"
const COMMAND_TYPE_SET_SUBTITLES = "setSubtitlesTrack"
const COMMAND_TYPE_ON_USER_ACTIVITY = "onUserActivity"
' Special commands
const COMMAND_TYPE_SESSION_ID = "c"
const COMMAND_TYPE_G_SESSION_ID = "S"
' Dpad commands
const COMMAND_KEY_UP = "UP"
const COMMAND_KEY_DOWN = "DOWN"
const COMMAND_KEY_LEFT = "LEFT"
const COMMAND_KEY_RIGHT = "RIGHT"
const COMMAND_KEY_ENTER = "ENTER"
const COMMAND_KEY_BACK = "BACK"
' Fields
const FIELD_COUNT = "count"
const FIELD_OFS = "ofs"
const FIELD_COMMAND_NAME = "_sc"
const FIELD_STATE = "state"
const FIELD_VIDEO_ID = "videoId"
const FIELD_VIDEO_IDS = "videoIds"
const FIELD_EVENT_DETAILS = "eventDetails"
const FIELD_LIST_ID = "listId"
const FIELD_CURRENT_TIME = "currentTime"
const FIELD_DURATION = "duration"
const FIELD_VOLUME = "volume"
const FIELD_MUTED = "muted"
const FIELD_CPN = "cpn"
const FIELD_CTT = "ctt"
const FIELD_CURRENT_INDEX = "currentIndex"
const FIELD_LOADED_TIME = "loadedTime"
const FIELD_SEEKABLE_START_TIME = "seekableStartTime"
const FIELD_SEEKABLE_END_TIME = "seekableEndTime"
const FIELD_HAS_PREVIOUS = "hasPrevious"
const FIELD_HAS_NEXT = "hasNext"
const FIELD_NEW_TIME = "newTime"
enum PlayerState
UNSTARTED = -1
ENDED = 0
PLAYING = 1
PAUSED = 2
BUFFERING = 3
STOPPED = 4
VIDEO_CUED = 5
ADVERTISEMENT = 1081
UNCONFIRMED = -8002
ERROR = -8003
UNKNOWN = -8001
end enum
@@ -0,0 +1,64 @@
import "pkg:/components/Services/LoungeService/LoungeApi.bs"
import "pkg:/source/services/HttpClient.bs"
import "pkg:/source/utils/StringUtils.bs"
@asynctask
function LoungeGenerateManualPairingCodeTask(input as object) as object
loungeService = input.loungeService
if StringUtils.IsNullOrEmpty(input.loungeToken)
messagePort = CreateObject("roMessagePort")
loungeService.observeFieldScoped("loungeToken", messagePort)
loungeService.join = true
message = wait(30000, messagePort)
loungeService.unobserveFieldScoped("loungeToken")
if message = invalid or StringUtils.IsNullOrEmpty(message.GetData())
return {
"success": false
"error": "Couldn't join lounge"
}
end if
input.screenId = loungeService.screenId
input.loungeToken = loungeService.loungeToken
end if
bodyParams = {
"lounge_token": input.loungeToken
"screen_id": input.screenId
"screen_name": input.screenName
"device_id": input.deviceId
}
for each key in bodyParams
if StringUtils.IsNullOrEmpty(bodyParams[key])
return {
"success": false
"error": key + " is empty"
}
end if
end for
bodyParams["access_type"] = "permanent"
bodyParams["app"] = "Playlet"
baseUrl = "https://www.youtube.com/api/lounge/pairing/get_pairing_code?ctx=pair"
body = UrlUtils.GetUrlEncodedForm(bodyParams)
request = HttpClient.Post(baseUrl, body)
request.Header("Content-Type", "application/x-www-form-urlencoded")
response = request.Await()
if not response.IsSuccess()
return {
"success": false
"error": response.ErrorMessage()
}
end if
code = response.Text()
return {
"success": true
"code": code
}
end function
@@ -0,0 +1,126 @@
import "pkg:/components/Services/LoungeService/LoungeConstants.bs"
import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/Types.bs"
namespace LoungeMessages
function OnHasPreviousNextChanged(hasPrevious as boolean, hasNext as boolean) as object
message = {
commandType: COMMAND_ON_PREVIOUS_NEXT_CHANGE
}
commandArgs = {}
commandArgs[FIELD_HAS_PREVIOUS] = hasPrevious
commandArgs[FIELD_HAS_NEXT] = hasNext
message.commandArgs = commandArgs
return message
end function
function OnStateChange(player as object, overrides = invalid as object) as object
message = {
commandType: COMMAND_ON_STATE_CHANGE
}
commandArgs = {}
if player = invalid
commandArgs[FIELD_STATE] = PlayerState.UNSTARTED
message.commandArgs = commandArgs
return message
end if
commandArgs[FIELD_STATE] = GetPlayerState(player)
commandArgs[FIELD_CURRENT_TIME] = ValidDouble(player.position)
commandArgs[FIELD_SEEKABLE_START_TIME] = 0
content = player.content
if content <> invalid
metadata = content.metadata
if metadata <> invalid
lengthSeconds = metadata.lengthSeconds
if IsInt(lengthSeconds)
commandArgs[FIELD_DURATION] = lengthSeconds
commandArgs[FIELD_SEEKABLE_END_TIME] = lengthSeconds
if commandArgs[FIELD_STATE] = PlayerState.PLAYING or commandArgs[FIELD_STATE] = PlayerState.PAUSED or commandArgs[FIELD_STATE] = PlayerState.BUFFERING
commandArgs[FIELD_LOADED_TIME] = lengthSeconds
end if
end if
end if
end if
if overrides <> invalid
commandArgs.Append(overrides)
end if
message.commandArgs = commandArgs
return message
end function
function NowPlaying(player as object, overrides = invalid as object) as object
message = {
commandType: COMMAND_NOW_PLAYING
}
if player = invalid
return message
end if
commandArgs = {}
commandArgs[FIELD_CURRENT_TIME] = ValidDouble(player.position)
commandArgs[FIELD_SEEKABLE_START_TIME] = 0
commandArgs[FIELD_CURRENT_INDEX] = 0
commandArgs[FIELD_STATE] = GetPlayerState(player)
content = player.content
if content <> invalid
metadata = content.metadata
if metadata <> invalid
lengthSeconds = metadata.lengthSeconds
if IsInt(lengthSeconds)
commandArgs[FIELD_DURATION] = lengthSeconds
commandArgs[FIELD_SEEKABLE_END_TIME] = lengthSeconds
if commandArgs[FIELD_STATE] = PlayerState.PLAYING or commandArgs[FIELD_STATE] = PlayerState.PAUSED or commandArgs[FIELD_STATE] = PlayerState.BUFFERING
commandArgs[FIELD_LOADED_TIME] = lengthSeconds
end if
end if
videoId = metadata.videoId
if not StringUtils.IsNullOrEmpty(videoId)
commandArgs[FIELD_VIDEO_ID] = videoId
end if
end if
end if
if overrides <> invalid
commandArgs.Append(overrides)
end if
message.commandArgs = commandArgs
return message
end function
function GetPlayerState(player as object) as PlayerState
if player = invalid
return PlayerState.UNSTARTED
end if
state = player.state
if state = "playing"
return PlayerState.PLAYING
else if state = "paused"
return PlayerState.PAUSED
else if state = "buffering"
return PlayerState.BUFFERING
else if state = "finished"
return PlayerState.ENDED
else if state = "stopped" or state = "stopping"
return PlayerState.STOPPED
end if
return PlayerState.UNSTARTED
end function
end namespace
@@ -0,0 +1,132 @@
import "pkg:/components/parts/AutoBind/OnNodeReadyNoOp.bs"
import "pkg:/components/Services/LoungeService/LoungeApi.bs"
' TODO:P0
' 1. Add a section about the lounge in the privacy policy
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)
m.top.isRunning = false
return
end if
m.top.screenId = screenId
loungeToken = api.GetToken()
if StringUtils.IsNullOrEmpty(loungeToken)
m.top.isRunning = false
return
end if
m.top.loungeToken = loungeToken
m.top.observeField("outgoingMessages", messagePort)
if not api.GetSessionData()
m.top.unobserveField("outgoingMessages", messagePort)
m.top.isRunning = false
return
end if
api.SaveCurrentLoungeData()
api.FetchCommandsRpc(messagePort)
m.top.shouldQuit = false
isOpen = false
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)
api.ProcessPendingOutgoingMessages()
if not isOpen
sleep(3000)
api.FetchCommandsRpc(messagePort)
end if
end while
m.top.unobserveField("outgoingMessages", messagePort)
m.top.isRunning = false
end function
@@ -0,0 +1,24 @@
<component name="LoungeService" extends="Task" includes="AutoBind">
<interface>
<field id="deviceId" type="string" />
<!-- We treat device name and screen name the same -->
<field id="deviceName" type="string" />
<field id="screenId" type="string" />
<field id="loungeToken" type="string" />
<field id="devices" type="assocarray" />
<field id="join" type="boolean" alwaysNotify="true" />
<field id="outgoingMessages" type="array" alwaysNotify="true" />
<field id="videoQueue" type="node" />
<field id="notifications" type="node" />
<field id="invidious" type="node" />
<field id="isRunning" type="boolean" />
<function name="StartService" />
<function name="StopService" />
<field id="shouldQuit" type="boolean" alwaysNotify="true" />
</interface>
</component>
@@ -0,0 +1,110 @@
import "pkg:/components/Services/Invidious/InvidiousService.bs"
import "pkg:/components/Services/Invidious/InvidiousToContentNode.bs"
import "pkg:/components/Services/LoungeService/LoungeConstants.bs"
import "pkg:/components/VideoQueue/Notifications/VideoQueueNotificationUtils.bs"
namespace LoungeVideoQueue
function SetPlaylist(videoQueueNode as object, invService as object, playlistData as object)
HandleLoungePlaylist(videoQueueNode, invService, playlistData)
end function
function UpdatePlaylist(videoQueueNode as object, invService as object, playlistData as object)
HandleLoungePlaylist(videoQueueNode, invService, playlistData)
end function
function HandleLoungePlaylist(videoQueueNode as object, invService as object, playlistData as object) as void
videoIds = playlistData[FIELD_VIDEO_IDS]
if StringUtils.IsNullOrEmpty(videoIds)
videoQueueNode.clearQueue = true
return
end if
videoIds = videoIds.Split(",")
queueContent = videoQueueNode.content
currentQueueNodes = queueContent.getChildren(-1, 0)
queueNodesDict = {}
for each node in currentQueueNodes
queueNodesDict[node.id] = node
end for
instance = invalid
newQueueNodes = []
for each vId in videoIds
if queueNodesDict.DoesExist(vId)
newQueueNodes.Push(queueNodesDict[vId])
else
payload = {
"type": "video"
"videoId": vId
}
if instance = invalid
instance = invService.GetInstance()
end if
contentNode = InvidiousContent.ToVideoContentNode(invalid, payload, instance)
newQueueNodes.Push(contentNode)
end if
end for
index = -1
currentIndex = playlistData[FIELD_CURRENT_INDEX]
if IsString(currentIndex)
currentIndex = CInt(Val(currentIndex))
index = currentIndex
else
index = videoQueueNode.index
end if
videoQueueNode.setQueueAndIndex = {
videoNodes: newQueueNodes
index: index
}
videoId = playlistData[FIELD_VIDEO_ID]
timestamp = playlistData[FIELD_CURRENT_TIME]
if not StringUtils.IsNullOrEmpty(videoId)
if not StringUtils.IsNullOrEmpty(timestamp)
timestamp = CInt(Val(timestamp))
if timestamp > 0
node = newQueueNodes[index]
node.timestamp = timestamp
end if
end if
videoQueueNode.play = true
end if
if StringUtils.IsNullOrEmpty(videoId)
eventDetails = playlistData[FIELD_EVENT_DETAILS]
if IsString(eventDetails)
eventDetails = ParseJson(eventDetails)
end if
if eventDetails <> invalid and eventDetails["eventType"] = "VIDEO_ADDED"
eventVideoId = eventDetails[FIELD_VIDEO_ID]
if not StringUtils.IsNullOrEmpty(eventVideoId)
preferences = videoQueueNode.preferences
queueNotifications = preferences["misc.queue_notifications"]
if queueNotifications
payload = {
"type": "video"
"videoId": eventVideoId
}
if instance = invalid
instance = invService.GetInstance()
end if
node = InvidiousContent.ToVideoContentNode(invalid, payload, instance)
notifications = videoQueueNode.notifications
hintVisible = videoQueueNode.player = invalid or not videoQueueNode.videoContainer.fullscreen
VideoQueue.ShowNotifcation(notifications, node, hintVisible)
end if
end if
end if
end if
end function
end namespace
@@ -0,0 +1,50 @@
import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/Types.bs"
' TODO:P2 a lot of shared logic with the SponsorBlock notification, should be refactored into a common notification
function Init()
m.translationAnimation = m.top.findNode("translationAnimation")
m.translationAnimationInterpolator = m.top.findNode("translationAnimationInterpolator")
m.animationTimer = m.top.findNode("animationTimer")
m.top.translation = [1280, 20]
m.translationAnimation.observeField("state", FuncName(OnAnimationState))
m.animationTimer.observeField("fire", FuncName(OnAnimationTimer))
end function
function OnShow()
AnimateIn()
end function
function OnAnimationTimer()
AnimateOut()
end function
function AnimateIn()
m.translationAnimation.unobserveField("state")
m.animationTimer.control = "stop"
m.animationTimer.control = "start"
m.translationAnimation.observeField("state", FuncName(OnAnimationState))
Animate(false)
end function
function AnimateOut()
Animate(true)
end function
function Animate(reverse as boolean) as void
' We are already animating in the requested direction
if m.translationAnimationInterpolator.reverse = reverse and m.translationAnimation.control <> "none"
return
end if
m.translationAnimationInterpolator.reverse = reverse
m.translationAnimation.control = "start"
end function
function OnAnimationState()
if m.translationAnimation.state = "stopped" and m.translationAnimationInterpolator.reverse = true
m.top.getParent().removeChild(m.top)
end if
end function
@@ -0,0 +1,53 @@
<component name="DeviceConnectedNotification" extends="Group">
<interface>
<field id="thumbnail" type="uri" alias="thumbnailPoster.uri" />
<field id="line1" type="string" alias="line1Label.text" />
<field id="show" type="boolean" alwaysNotify="true" onChange="OnShow" />
</interface>
<children>
<Poster
width="350"
height="100"
opacity="0.9"
blendColor="#414141"
uri="pkg:/images/white.9.png">
<CirclePoster
id="thumbnailPoster"
width="80"
height="80"
failedBitmapUri="pkg:/images/icons/user.png"
translation="[10,10]" />
<LayoutGroup
itemSpacings="[10]"
translation="[100,10]">
<Label
width="230"
font="font:SmallestBoldSystemFont"
horizAlign="center"
text="Device connected">
<Font role="font" uri="font:BoldSystemFontFile" size="22" />
</Label>
<Label
id="line1Label"
width="230"
font="font:SmallestSystemFont"
horizAlign="center" />
</LayoutGroup>
</Poster>
<Animation
id="translationAnimation"
duration="0.3"
optional="true">
<Vector2DFieldInterpolator
id="translationAnimationInterpolator"
key="[0.0, 0.5, 1.0]"
keyValue="[ [1280.0, 20.0], [1095.0, 20.0], [910.0, 20.0] ]"
fieldToInterp="DeviceConnectedNotification.translation" />
</Animation>
<Timer
id="animationTimer"
duration="3" />
</children>
</component>
@@ -0,0 +1,35 @@
namespace LoungeDeviceConnected
const NOTIFICATION_NODE_ID = "DeviceConnectedNotification"
function ShowNotifcation(notifications as object, name as dynamic, thumbnail as dynamic) as void
notification = notifications.findNode(NOTIFICATION_NODE_ID)
if notification = invalid
notification = notifications.createChild("DeviceConnectedNotification")
notification.id = NOTIFICATION_NODE_ID
end if
if StringUtils.IsNullOrEmpty(name)
name = "Device"
end if
notification.line1 = name
if StringUtils.IsNullOrEmpty(thumbnail)
thumbnail = "pkg:/images/icons/user.png"
end if
notification.thumbnail = thumbnail
notification.show = true
end function
function RemoveNotifcation(notifications as object) as void
notification = notifications.findNode(NOTIFICATION_NODE_ID)
if notification <> invalid
notifications.RemoveChild(notification)
end if
end function
function SetVisible(notifications as object, visible as boolean)
notification = notifications.findNode(NOTIFICATION_NODE_ID)
if notification <> invalid
notification.visible = visible
end if
end function
end namespace
@@ -1,5 +1,3 @@
import "pkg:/components/VideoPlayer/VideoUtils.bs"
namespace SponsorBlock
const NOTIFICATION_NODE_ID = "SponsorBlockNotification"