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

@@ -0,0 +1,205 @@
import "pkg:/components/parts/AutoBind/OnNodeReadyNoOp.bs"
import "pkg:/source/services/ApplicationInfo.bs"
import "pkg:/source/utils/Logging.bs"
import "pkg:/source/utils/Types.bs"
function Init()
m.top.functionName = "DialServerLoop"
end function
function StartServer(_unused as dynamic) as boolean
if m.top.isRunning = true
return true
end if
m.top.control = "run"
return true
end function
function StopServer(_unused as dynamic) as void
if m.top.isRunning = false
return
end if
m.top.shouldQuit = true
end function
function DialServerLoop() as void
webServer = m.top.webServer
m.deviceId = m.top.loungeService.deviceId
messagePort = createobject("roMessagePort")
udp = createobject("roDatagramSocket")
udp.setMessagePort(messagePort)
addr = createobject("roSocketAddress")
addr.setPort(1900)
udp.setAddress(addr)
addr.SetHostName("239.255.255.250")
udp.setSendToAddress(addr)
udp.notifyReadable(true)
ssdpResponse = invalid
' For each address, we will keep track of the last X times we sent a response.
' If we responded to a message from an address more than X times in the last Y seconds, we will not respond again.
timeThreshold = 5000
countThreshold = 3
timers = {}
timer = createobject("roTimespan")
m.top.shouldQuit = false
m.top.observeField("shouldQuit", messagePort)
while udp.eOK()
message = wait(10000, messagePort)
messageType = type(message)
if messageType = "roSGNodeEvent"
field = message.GetField()
if field = "shouldQuit"
exit while
end if
end if
if messageType <> "roSocketEvent"
continue while
end if
if message.getSocketID() <> udp.getID()
continue while
end if
if not udp.isReadable()
continue while
end if
messageStr = udp.receiveStr(512)
ssdpMessage = ParseSsdpMessage(messageStr)
if not ShouldRespondToMessage(ssdpMessage)
continue while
end if
peerAddress = udp.GetReceivedFromAddress()
address = peerAddress.GetAddress()
host = peerAddress.GetHostName()
if timers[host] = invalid
timers[host] = []
LogInfo(`Received message from ${address}:`, ssdpMessage)
LogInfo(`No further messages from ${host} will be logged at info level. If you need to debug, please enable debug logging.`)
else
LogDebug(`Received message from ${address}:`, ssdpMessage)
end if
timerForHost = timers[host]
now = timer.TotalMilliseconds()
' Remove any timers that are older than timeThreshold
while timerForHost.Count() > 0 and now - timerForHost[0] > timeThreshold
timerForHost.Shift()
end while
if timerForHost.Count() >= countThreshold
LogDebug(`Ignoring message from ${address} - too spammy`)
continue while
end if
timerForHost.Push(now)
ssdpResponse = CreateSsdpResponse(ssdpMessage, webServer)
udp.setSendToAddress(peerAddress)
udp.sendStr(ssdpResponse)
end while
udp.close()
m.top.isRunning = false
LogInfo("Server stopped")
end function
function ParseSsdpMessage(message as string) as object
if not IsString(message) or not message.StartsWith("M-SEARCH")
return invalid
end if
lines = message.split(`\r\n`)
operation = lines[0]
parts = operation.split(" ")
if parts.Count() <> 3
return invalid
end if
ssdp = {}
ssdp["method"] = parts[0]
ssdp["uri"] = parts[1]
ssdp["protocol"] = parts[2]
headers = {}
for i = 1 to lines.Count() - 1
line = lines[i]
if line = ""
continue for
end if
colonIndex = line.InStr(":")
if colonIndex = -1
continue for
end if
key = line.Left(colonIndex).trim()
value = line.Mid(colonIndex + 1).trim()
headers[key] = value
end for
ssdp["headers"] = headers
return ssdp
end function
function ShouldRespondToMessage(ssdp as object) as boolean
if ssdp = invalid
return false
end if
if ssdp["method"] <> "M-SEARCH" or ssdp["uri"] <> "*" or ssdp["protocol"] <> "HTTP/1.1"
return false
end if
headers = ssdp["headers"]
if headers["MAN"] <> `"ssdp:discover"`
return false
end if
if headers["ST"] <> "urn:dial-multiscreen-org:service:dial:1" and headers["ST"] <> "ssdp:all"
return false
end if
return true
end function
function CreateSsdpResponse(ssdp as object, webServer as object) as string
libVersion = m._libVersion
if libVersion = invalid
' We're supposed to pass the ApplicationInfo node, but since we're not going to use it, we can pass invalid
appInfo = new ApplicationInfo(invalid)
if libVersion = invalid
libVersion = appInfo.GetLibVersion()
m._libVersion = libVersion
end if
end if
webServerAddress = m._webServerAddress
if webServerAddress = invalid
webServerAddress = webServer@.GetServerAddress()
m._webServerAddress = webServerAddress
end if
msg = `HTTP/1.1 200 OK\r\n`
msg += `LOCATION: ${webServerAddress}/dial/${m.deviceId}/device-description.xml\r\n`
msg += `ST: ${ssdp.headers.ST}\r\n`
msg += `SERVER: Playlet Lib Dial Server ${libVersion} \r\n`
msg += `USN: uuid:${m.deviceId}::${ssdp.headers.ST}\r\n`
msg += `CACHE-CONTROL: no-cache, no-store, max-age=0, must-revalidate\r\n`
msg += `EXT: \r\n`
msg += `\r\n`
return msg
end function
@@ -0,0 +1,11 @@
<component name="DialServer" extends="Task" includes="AutoBind">
<interface>
<field id="webServer" type="node" />
<field id="loungeService" type="node" />
<field id="isRunning" type="boolean" />
<function name="StartServer" />
<function name="StopServer" />
<field id="shouldQuit" type="boolean" alwaysNotify="true" />
</interface>
</component>
@@ -0,0 +1,197 @@
import "pkg:/source/services/XmlObject.bs"
namespace Http
class DialRouter extends HttpRouter
function new(server as object)
super()
task = server.task
m.serverAddress = task@.GetServerAddress()
m.scene = task.getScene()
m.loungeService = task.loungeService
m.deviceId = m.loungeService.deviceId
m.deviceName = m.loungeService.deviceName
m.routes.push({ method: "GET", path: `/dial/${m.deviceId}/device-description.xml`, router: m, func: "GetDialManifest" })
m.routes.push({ method: "GET", path: `/dial/${m.deviceId}/YouTube`, router: m, func: "GetDialYouTube" })
m.routes.push({ method: "POST", path: `/dial/${m.deviceId}/YouTube`, router: m, func: "PostDialYouTube" })
m.routes.push({ method: "DELETE", path: `/dial/${m.deviceId}/YouTube/run`, router: m, func: "CloseChannel" })
end function
' @get("/dial/device-description.xml")
function GetDialManifest(context as object) as boolean
response = context.response
xmlContent = m.GenerateDialManifest()
response.http_code = 200
response.SetBodyDataString(xmlContent)
response.ContentType(`text/xml; charset="utf-8"`)
response.headers["Application-URL"] = `${m.serverAddress}/dial/${m.deviceId}`
response.headers["Cache-Control"] = "no-cache, no-store, max-age=0, must-revalidate"
return true
end function
' @get("/dial/YouTube")
function GetDialYouTube(context as object) as boolean
response = context.response
xmlContent = m.GenerateDialYouTube()
response.http_code = 200
response.SetBodyDataString(xmlContent)
response.ContentType(`text/xml; charset="utf-8"`)
response.headers["Cache-Control"] = "no-cache, no-store, max-age=0, must-revalidate"
return true
end function
' @post("/dial/YouTube")
function PostDialYouTube(context as object) as boolean
request = context.request
response = context.response
fields = UrlUtils.GetUrlDecodedForm(request.body)
pairingCode = fields["pairingCode"]
if StringUtils.IsNullOrEmpty(pairingCode)
response.Default(400, "Bad Request")
return true
end if
theme = fields["theme"]
if not IsString(theme) or theme <> "cl"
response.Default(400, "Bad Request")
return true
end if
loungeToken = m.loungeService.loungeToken
if StringUtils.IsNullOrEmpty(loungeToken)
messagePort = CreateObject("roMessagePort")
m.loungeService.observeFieldScoped("loungeToken", messagePort)
m.loungeService.join = true
message = wait(30000, messagePort)
m.loungeService.unobserveFieldScoped("loungeToken")
if message = invalid or StringUtils.IsNullOrEmpty(message.GetData())
response.Default(500, "Couldn't join lounge")
return true
end if
end if
registerUrl = "https://www.youtube.com/api/lounge/pairing/register_pairing_code"
registerBody = {
"app": "Playlet"
"pairing_code": pairingCode
"screen_id": m.loungeService.screenId
"screen_name": m.deviceName
"device_id": m.deviceId
}
body = UrlUtils.GetUrlEncodedForm(registerBody)
req = HttpClient.Post(registerUrl, body)
req.Header("Content-Type", "application/x-www-form-urlencoded")
res = req.Await()
if not res.IsSuccess()
response.Default(500, "Internal Server Error")
return true
end if
response.Default(200, "Ok")
return true
end function
' @delete("/dial/YouTube/run")
function CloseChannel(context as object) as boolean
response = context.response
response.Default(200, "Shutting down app...")
m.scene.exitChannel = true
return true
end function
function GenerateDialManifest() as string
if m._dialXml <> invalid
return m._dialXml
end if
xml = new XmlObject()
if xml.Node("root", { "xmlns": "urn:schemas-upnp-org:device-1-0" })
if xml.Node("specVersion")
xml.TextNode("major", "1")
xml.TextNode("minor", "0")
xml.End()
end if
if xml.Node("device")
xml.TextNode("deviceType", "urn:dial-multiscreen-org:device:dial:1")
xml.TextNode("friendlyName", m.deviceName)
xml.TextNode("manufacturer", "Generic")
xml.TextNode("modelName", "Generic")
xml.TextNode("UDN", "uuid:" + m.deviceId)
if xml.Node("serviceList")
if xml.Node("service")
xml.TextNode("serviceType", "urn:dial-multiscreen-org:service:dial:1")
xml.TextNode("serviceId", "urn:dial-multiscreen-org:serviceId:dial")
xml.EmptyNode("controlURL")
xml.EmptyNode("eventSubURL")
xml.EmptyNode("SCPDURL")
xml.End()
end if
xml.End()
end if
xml.End()
end if
xml.End()
end if
m._dialXml = xml.ToXmlString()
return m._dialXml
end function
function GenerateDialYouTube() as string
screenId = m.loungeService.screenId
loungeToken = m.loungeService.loungeToken
if m._dialYouTubeXml <> invalid
if m._dialYoutubeScreenId = screenId and m._dialYoutubeLoungeToken = loungeToken
return m._dialYouTubeXml
end if
end if
xml = new XmlObject()
if xml.Node("service", { "dialVer": "1.7", "xmlns": "urn:dial-multiscreen-org:schemas:dial" })
xml.TextNode("name", "YouTube")
xml.EmptyNode("options", { "allowStop": "true" })
xml.TextNode("state", "running")
xml.EmptyNode("link", { "rel": "run", "href": "run" })
if not StringUtils.IsNullOrEmpty(screenId) and not StringUtils.IsNullOrEmpty(loungeToken)
if xml.Node("additionalData")
xml.TextNode("theme", "cl")
xml.TextNode("deviceId", m.deviceId)
xml.TextNode("screenId", screenId)
xml.TextNode("loungeToken", loungeToken)
xml.End()
end if
end if
xml.End()
end if
m._dialYouTubeXml = xml.ToXmlString()
m._dialYoutubeScreenId = screenId
m._dialYoutubeLoungeToken = loungeToken
return m._dialYouTubeXml
end function
end class
end namespace
@@ -1,15 +1,16 @@
import "pkg:/components/Services/Invidious/InvidiousToContentNode.bs"
import "pkg:/components/VideoPlayer/VideoUtils.bs"
import "pkg:/components/VideoQueue/VideoQueueUtils.bs"
import "pkg:/source/utils/MathUtils.bs"
namespace Http
class PlayQueueRouter extends HttpRouter
class VideoQueueRouter extends HttpRouter
function new(server as object)
super()
task = server.task
m.playQueueNode = task.playQueue
m.videoQueueNode = task.videoQueue
m.invidiousNode = task.invidious
m.invidiousService = new Invidious.InvidiousService(m.invidiousNode)
end function
@@ -18,7 +19,7 @@ namespace Http
function GetQueue(context as object) as boolean
response = context.response
queue = m.playQueueNode@.GetQueue()
queue = VideoQueueUtils.GetQueueDto(m.videoQueueNode)
response.Json(queue)
return true
end function
@@ -44,10 +45,15 @@ namespace Http
instance = m.invidiousService.GetInstance()
contentNode = InvidiousContent.ToRowCellContentNode(payload, instance)
m.playQueueNode@.AddToQueue(contentNode)
queue = m.playQueueNode@.GetQueue()
response.Json(queue)
nodeType = contentNode.type
if nodeType = "playlist"
m.videoQueueNode.addToQueuePlaylist = contentNode
else if nodeType = "video"
m.videoQueueNode.addToQueue = [contentNode]
end if
response.Default(204, "OK")
return true
end function
@@ -76,13 +82,18 @@ namespace Http
instance = m.invidiousService.GetInstance()
contentNode = InvidiousContent.ToRowCellContentNode(payload, instance)
playlistIndex = IsInt(payload.playlistIndex) ? payload.playlistIndex : -1
if contentNode.type = "playlist" and playlistIndex = -1
playlistIndex = 0
end if
nodeType = contentNode.type
'TODO:P1 play existing item by index instead of new item inserted
m.playQueueNode@.Play(contentNode, playlistIndex)
if nodeType = "playlist"
playlistIndex = MathUtils.Max(0, ValidInt(payload.playlistIndex))
m.videoQueueNode.playPlaylist = {
playlistNode: contentNode
playlistIndex: playlistIndex
}
else if nodeType = "video"
m.videoQueueNode.playVideo = contentNode
end if
response.Default(204, "OK")
return true
@@ -92,7 +103,8 @@ namespace Http
function ClearQueue(context as object) as boolean
response = context.response
m.playQueueNode@.Clear()
m.videoQueueNode.clearQueue = true
response.Default(204, "OK")
return true
end function
@@ -1,6 +1,7 @@
import "pkg:/components/ChannelView/ChannelUtils.bs"
import "pkg:/components/PlaylistView/PlaylistUtils.bs"
import "pkg:/components/Services/Invidious/InvidiousToContentNode.bs"
import "pkg:/components/VideoQueue/VideoQueueUtils.bs"
namespace Http
@@ -9,7 +10,9 @@ namespace Http
function new(server as object)
super()
m.appController = server.task.appController
task = server.task
m.appController = task.appController
m.videoQueue = task.videoQueue
end function
@get("/api/view/open")
@@ -23,15 +26,15 @@ namespace Http
if not StringUtils.IsNullOrEmpty(playlistId)
contentNode = InvidiousContent.ToPlaylistContentNode(invalid, { playlistId: playlistId }, invalid)
PlaylistUtils.Open(contentNode, m.appController)
if VideoUtils.IsVideoPlayerOpen() and VideoUtils.IsVideoPlayerFullScreen()
VideoUtils.ToggleVideoPictureInPicture()
if VideoQueueUtils.IsVideoPlayerOpen(m.videoQueue) and VideoQueueUtils.IsVideoPlayerFullScreen(m.videoQueue)
VideoQueueUtils.ToggleVideoPictureInPicture(m.videoQueue)
end if
response.Default(204, "OK")
else if not StringUtils.IsNullOrEmpty(authorId)
contentNode = InvidiousContent.ToChannelContentNode(invalid, { authorId: authorId }, invalid)
ChannelUtils.Open(contentNode, m.appController)
if VideoUtils.IsVideoPlayerOpen() and VideoUtils.IsVideoPlayerFullScreen()
VideoUtils.ToggleVideoPictureInPicture()
if VideoQueueUtils.IsVideoPlayerOpen(m.videoQueue) and VideoQueueUtils.IsVideoPlayerFullScreen(m.videoQueue)
VideoQueueUtils.ToggleVideoPictureInPicture(m.videoQueue)
end if
response.Default(204, "OK")
else
@@ -1,15 +1,16 @@
import "pkg:/components/parts/AutoBind/OnNodeReadyNoOp.bs"
import "pkg:/components/Web/PlayletWebServer/Middleware/BookmarksRouter.bs"
import "pkg:/components/Web/PlayletWebServer/Middleware/DashRouter.bs"
import "pkg:/components/Web/PlayletWebServer/Middleware/DialRouter.bs"
import "pkg:/components/Web/PlayletWebServer/Middleware/HomeLayoutRouter.bs"
import "pkg:/components/Web/PlayletWebServer/Middleware/HomeRouter.bs"
import "pkg:/components/Web/PlayletWebServer/Middleware/InvidiousRouter.bs"
import "pkg:/components/Web/PlayletWebServer/Middleware/PlayletLibUrlsRouter.bs"
import "pkg:/components/Web/PlayletWebServer/Middleware/PlayQueueRouter.bs"
import "pkg:/components/Web/PlayletWebServer/Middleware/PreferencesRouter.bs"
import "pkg:/components/Web/PlayletWebServer/Middleware/RegistryRouter.bs"
import "pkg:/components/Web/PlayletWebServer/Middleware/SearchHistoryRouter.bs"
import "pkg:/components/Web/PlayletWebServer/Middleware/StateApiRouter.bs"
import "pkg:/components/Web/PlayletWebServer/Middleware/VideoQueueRouter.bs"
import "pkg:/components/Web/PlayletWebServer/Middleware/ViewRouter.bs"
import "pkg:/components/Web/WebServer/Middleware/CorsMiddleware.bs"
import "pkg:/components/Web/WebServer/Middleware/EtagMiddleware.bs"
@@ -40,12 +41,13 @@ function SetupRoutes(server as object)
server.UseRouter(new Http.DashRouter(server))
server.UseRouter(new Http.PreferencesRouter(server))
server.UseRouter(new Http.InvidiousRouter(server))
server.UseRouter(new Http.PlayQueueRouter(server))
server.UseRouter(new Http.VideoQueueRouter(server))
server.UseRouter(new Http.BookmarksRouter(server))
server.UseRouter(new Http.HomeLayoutRouter(server))
server.UseRouter(new Http.ViewRouter(server))
server.UseRouter(new Http.SearchHistoryRouter(server))
server.UseRouter(new Http.PlayletLibUrlsRouter(server))
server.UseRouter(new Http.DialRouter(server))
etags = new Http.EtagUtils()
server.UseRouter(new Http.HttpStaticFilesRouter("/", "libpkg:/www", etags, { staticFiles: true }))
@@ -4,8 +4,9 @@
<field id="preferences" type="node" />
<field id="invidious" type="node" />
<field id="applicationInfo" type="node" />
<field id="playQueue" type="node" />
<field id="videoQueue" type="node" />
<field id="bookmarks" type="node" />
<field id="loungeService" type="node" />
<function name="GetServerAddress" />
</interface>
</component>