Compare commits

..
15 Commits
Author SHA1 Message Date
spaghet b5a921f206 Loader title back to Playlet (fork adds a Piped backend; the app is still Playlet), build 00013 2026-11-24 18:19:25 -05:00
spaghet bc8e70788b Loader build_version 00012 2026-11-24 18:12:35 -05:00
spaghet 2401522aa6 Loader manifest: debug lib URL -> piped-backend branch (main is now pristine upstream mirror) 2026-11-24 18:11:56 -05:00
spaghet e52f24c2b6 dist: lib 1795496523 LIB-24 (moved from main; main is pristine upstream mirror) 2026-11-24 18:11:40 -05:00
spaghet 611e5fd373 Branding: real Piped logo (from frontend container) + profile card picks piped mark by backend URL 2026-11-24 00:02:56 -05:00
spaghet fcd21e72e5 Piped login: real username from /feed/rss subtitle (Split-based parse); profiles DELETE needs X-Playlet header + urlencoded id 2026-11-23 23:51:54 -05:00
spaghet da85f182bb Piped login: tolerate duplicate nonce query param (array values), idempotent replay of the just-issued login 2026-11-23 22:36:07 -05:00
spaghet a79e820f2d Piped login: persist nonce ring to registry, honor phone-carried nonce, actionable error pages 2026-11-23 22:24:36 -05:00
spaghet 89502757f0 Piped login dialog: relabel in OnNodeReady (loginKind set after Init); profile survives app restart 2026-11-23 22:02:38 -05:00
spaghet 40140e7e29 Piped login: throttle-key bust on authed upstream GETs, session-reject double-probe, /login form param, authLog probe tracing 2026-11-23 21:57:26 -05:00
spaghet 58c11ea07b Rename channel title to Piped (fork branding) 2026-11-23 14:37:36 -05:00
spaghet be8c79c3d1 Piped backend: absolute HLS URI rewrite, roLongInt-safe epoch conversion, /manifest endpoint 2026-11-23 14:35:27 -05:00
spaghet a30bf73d0f Fork default: backend.selected = piped 2026-11-23 12:40:53 -05:00
spaghet ee36c76e8f Add Piped backend: translation router + client wiring
- PipedBackendRouter serves Invidious-shaped /api/v1 JSON on the local
  web server at /playlet-piped-backend, translating from a real Piped
  instance (trending/search/suggestions/videos/comments/channels/
  playlists/stats; auth endpoints return unsupported for now).
- PipedToInvidious converters incl. HLS-first playback metadata
  (Piped's hls master via proxy.piped instance; muxed mp4 fallback)
  and previewFrames -> Playlet storyboard shape.
- preferences: backend.selected gains 'piped'; new piped.instance
  (default https://api.piped.spaghet.io).
- InvidiousService.GetInstance routes backend=piped to the local
  translation router; ResolveBackendId returns 'piped'.
2026-11-23 12:39:58 -05:00
Brahim Hadriche 4bd5c11f42 [skip ci] changelog typo 2026-11-21 12:08:54 -05:00
19 changed files with 2164 additions and 10 deletions

No files matched your search

+1 -1
View File
@@ -12,7 +12,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- DRM playback errors on certain TVs, by filtering out FairPlay-only streams
- Player seek bar and backdrop missing on some devices
- Missing titles in shorts
- Always set set seek mode to `accurate`
- Always set seek mode to `accurate`
## [0.48.10] - 2026-10-17
Binary file not shown.
+2 -2
View File
@@ -3,7 +3,7 @@ title=Playlet
# Do not update version manually, it is auto updated from package.json
major_version=0
minor_version=48
build_version=00011
build_version=00013
rsg_version=1.3
@@ -40,7 +40,7 @@ requires_widevine_version=1.0
playlet_lib_squashfs_remote_url=https://github.com/iBicha/playlet/releases/latest/download/playlet-lib.squashfs.pkg
playlet_lib_zip_remote_url=https://github.com/iBicha/playlet/releases/latest/download/playlet-lib.zip
playlet_lib_zip_embedded_url=pkg:/lib/playlet-lib.zip
playlet_lib_zip_debug_url=http://DEBUG_HOST_IP_ADDRESS:8086/playlet-lib.zip
playlet_lib_zip_debug_url=https://gitea.spaghet.io/spaghet/playlet-piped/raw/branch/piped-backend/piped/playlet-lib-1795496523.zip
git_commit_sha=unknown
@@ -7,6 +7,9 @@ function Init()
m.urlLabel = m.top.findNode("urlLabel")
m.qrCode = m.top.findNode("QrCodePoster")
' loginKind is assigned by the caller AFTER CreateObject returns, so any
' relabeling based on it must live in OnNodeReady, never here.
m.top.width = "920"
m.top.observeFieldScoped("buttonSelected", FuncName(Close))
@@ -15,10 +18,21 @@ function Init()
end function
function OnNodeReady()
if ValidString(m.top.loginKind) = "piped"
m.top.findNode("dlgTitle").primaryTitle = "Login to Piped"
m.top.findNode("bodyLine1").text = "Login to Piped in order to view Subscriptions and Playlists."
m.top.findNode("bodyLine2").text = "Sign in from your phone with SSO, or with a Piped username and password."
end if
address = m.webserver@.GetServerAddress()
isValidAddress = not StringUtils.IsNullOrEmpty(address)
if isValidAddress
url = `${address}/invidious/login`
loginKind = ValidString(m.top.loginKind)
if loginKind = "piped"
url = `${address}/piped/login`
else
url = `${address}/invidious/login`
end if
profileId = m.top.profileId
if not StringUtils.IsNullOrEmpty(profileId)
url = UrlUtils.AppendQueryParams(url, { profile: profileId })
@@ -4,13 +4,14 @@
<field id="profilesService" type="node" bind="/ProfilesService" />
<field id="url" type="string" onChange="OnUrlSet" />
<field id="profileId" type="string" />
<field id="loginKind" type="string" value="invidious" />
<field id="alwaysOnTop" type="boolean" />
</interface>
<children>
<StdDlgTitleArea primaryTitle="Login to Invidious" />
<StdDlgTitleArea id="dlgTitle" primaryTitle="Login to Invidious" />
<StdDlgContentArea>
<StdDlgTextItem text="Login to Invidious in order to view Subscriptions, Playlists, and use the Watch history." />
<StdDlgTextItem text="Please note that an Invidious account is different from a YouTube account." />
<StdDlgTextItem id="bodyLine1" text="Login to Invidious in order to view Subscriptions, Playlists, and use the Watch history." />
<StdDlgTextItem id="bodyLine2" text="Please note that an Invidious account is different from a YouTube account." />
</StdDlgContentArea>
<StdDlgButtonArea id="buttonArea">
<StdDlgButton text="OK" />
@@ -40,6 +40,8 @@
<BackendTypeContentNode id="BackendTypeYouTube" title="YouTube" backendLogoUri="pkg:/images/youtube-logo.png" />
<!-- bs:disable-next-line LOCALE_MISSING_TRANSLATIONS -->
<BackendTypeContentNode id="BackendTypeInvidious" title="Invidious" backendLogoUri="pkg:/images/invidious-logo.png" />
<!-- bs:disable-next-line LOCALE_MISSING_TRANSLATIONS -->
<BackendTypeContentNode id="BackendTypePiped" title="Piped" backendLogoUri="pkg:/images/piped-logo.png" />
</ContentNode>
</ContentNode>
</RowList>
@@ -11,6 +11,14 @@ namespace LoginUtils
m.top.getScene().dialog = dialog
end function
function ShowPipedLoginDialog(profileId = "" as string) as void
dialog = CreateObject("roSGNode", "InvidiousLoginDialog")
dialog.profileId = profileId
dialog.loginKind = "piped"
dialog@.BindNode()
m.top.getScene().dialog = dialog
end function
function ShowLoginWithYouTubeDisclaimerDialog() as void
dialog = DialogUtils.ShowDialogEx({
title: Tr(Locale.Dialogs.Disclaimer)
@@ -1,5 +1,6 @@
import "pkg:/source/utils/Locale.bs"
import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/Types.bs"
function Init()
m.normalFont = m.top.findNode("normalFont")
@@ -53,7 +54,13 @@ function OnContentSet() as void
backendType = content.type
if backendType = "invidious"
m.top.serverUrl = content.serverUrl
m.top.backendTypePosterUri = "pkg:/images/invidious-logo.png"
' A Piped-backed profile is stored as an invidious profile (token
' shape + auth machinery reuse); the local router URL is the tell.
if InStr(LCase(ValidString(content.serverUrl)), "piped") > 0
m.top.backendTypePosterUri = "pkg:/images/piped-logo.png"
else
m.top.backendTypePosterUri = "pkg:/images/invidious-logo.png"
end if
else if backendType = "youtube"
m.top.serverUrl = "YouTube"
m.top.backendTypePosterUri = "pkg:/images/youtube-logo.png"
@@ -56,6 +56,8 @@ function OnBackEndSelected(event as object) as void
selectedBackendType = event.getData()
if selectedBackendType = "BackendTypeInvidious"
OnLoginWithInvidiousSelected()
else if selectedBackendType = "BackendTypePiped"
LoginUtils.ShowPipedLoginDialog()
else if selectedBackendType = "BackendTypeYouTube"
LoginUtils.ShowLoginWithYouTubeDisclaimerDialog()
else
@@ -78,7 +78,13 @@ function OnContentSet() as void
backendType = content.type
if backendType = "invidious"
m.top.serverUrl = content.serverUrl
m.top.backendTypePosterUri = "pkg:/images/invidious-logo.png"
' A Piped-backed profile is stored as an invidious profile (token
' shape + auth machinery reuse); the local router URL is the tell.
if InStr(LCase(ValidString(content.serverUrl)), "piped") > 0
m.top.backendTypePosterUri = "pkg:/images/piped-logo.png"
else
m.top.backendTypePosterUri = "pkg:/images/invidious-logo.png"
end if
else if backendType = "youtube"
m.top.serverUrl = "YouTube"
m.top.backendTypePosterUri = "pkg:/images/youtube-logo.png"
@@ -16,6 +16,7 @@ namespace Invidious
const INSTANCES_API = "https://api.invidious.io/instances.json?sort_by=type,users"
const PLAYLET_BUILT_IN_INSTANCE = "http://127.0.0.1:8888/playlet-invidious-backend"
const PLAYLET_PIPED_BUILT_IN_INSTANCE = "http://127.0.0.1:8888/playlet-piped-backend"
const INSTANCE_EXAMPLE = "https://invidious.example.com"
const TOKEN_CALLBACK = "/invidious/token_callback"
@@ -82,6 +83,11 @@ namespace Invidious
end if
backend = m.preferences["backend.selected"]
if backend = "piped"
' Piped speaks its own API, not Invidious's; route through the
' local translation router that presents an Invidious-shaped facade.
return PLAYLET_PIPED_BUILT_IN_INSTANCE
end if
if backend = "invidious"
instance = m.GetInvidiousInstance()
if not StringUtils.IsNullOrEmpty(instance)
@@ -0,0 +1,744 @@
import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/Types.bs"
import "pkg:/source/utils/TimeUtils.bs"
' Converts Piped API responses (https://github.com/TeamPiped/Piped) into
' the JSON shapes Playlet expects from an Invidious /api/v1 backend.
' Piped serves its REST API at the instance root (no /api/v1 prefix).
namespace PipedToInvidious
function VideoFromPiped(item as object, index = invalid as dynamic) as object
videoId = ExtractVideoId(ValidString(item.url))
video = {
"videoId": videoId
"title": ValidString(item.title)
"author": ValidString(item.uploaderName)
"authorId": ExtractChannelId(ValidString(item.uploaderUrl))
"lengthSeconds": ValidInt(item.duration)
"viewCount": ValidInt(item.views)
"published": MillisToSeconds(item.uploaded)
"publishedText": ValidString(item.uploadedDate)
"videoThumbnails": ThumbnailsFromProxy(ValidString(item.thumbnail), videoId)
"type": "video"
"genre": []
}
if not StringUtils.IsNullOrEmpty(ValidString(item.uploaderAvatar))
video["authorThumbnails"] = [{ url: item.uploaderAvatar, width: 88, height: 88 }]
end if
if index <> invalid
video["index"] = index
end if
if item.isShort = true
video["isShort"] = true
end if
return video
end function
function VideosFromPiped(list as dynamic) as object
videos = []
if not IsArray(list)
return videos
end if
for each item in list
if type(item) = "roAssociativeArray" and item.type <> "channel" and item.type <> "playlist"
videos.push(VideoFromPiped(item))
end if
end for
return videos
end function
function PlaylistsFromPiped(list as dynamic) as object
playlists = []
if not IsArray(list)
return playlists
end if
for each item in list
if type(item) = "roAssociativeArray" and item.type = "playlist"
playlists.push({
"playlistId": ExtractPlaylistId(ValidString(item.url))
"title": ValidString(item.title)
"videoCount": ValidInt(item.videosCount)
"playlistThumbnail": ValidString(item.thumbnail)
"author": ValidString(item.uploaderName)
"authorId": ExtractChannelId(ValidString(item.uploaderUrl))
"type": "playlist"
})
end if
end for
return playlists
end function
function ChannelsFromPiped(list as dynamic) as object
channels = []
if not IsArray(list)
return channels
end if
for each item in list
if type(item) = "roAssociativeArray" and item.type = "channel"
channels.push({
"authorId": ExtractChannelId(ValidString(item.url))
"author": ValidString(item.title)
"authorThumbnail": ValidString(item.avatar)
"authorThumbnails": [{ url: ValidString(item.avatar), width: 88, height: 88 }]
"description": ValidString(item.description)
"subCount": ValidInt(item.subscribers)
"handle": ValidString(item.handle)
"verified": item.verified = true
"type": "channel"
})
end if
end for
return channels
end function
function GetFirstNonEmpty(first as string, second as string) as string
if first <> ""
return first
end if
return second
end function
function ChannelFromPiped(data as object, channelId as string) as object
' Piped /channel/{id} -> Invidious /api/v1/channels/{ucid}
result = {
"author": ValidString(data.name)
"authorId": GetFirstNonEmpty(ValidString(data.id), channelId)
"bannerUrl": ValidString(data.bannerUrl)
"description": ValidString(data.description)
"subCount": ValidInt(data.subscriberCount)
"relatedStreams": VideosFromPiped(data.relatedStreams)
"videos": VideosFromPiped(data.relatedStreams)
"tabs": ["videos"]
"tabsParams": { videos: "" }
"tabsTitles": {}
"authorBanners": []
}
nextpage = ValidString(data.nextpage)
if nextpage <> ""
result["continuation"] = Base64Encode(nextpage)
end if
if not StringUtils.IsNullOrEmpty(ValidString(data.bannerUrl))
result["authorBanners"] = [{ url: data.bannerUrl, width: 1060, height: 175 }]
end if
avatar = ValidString(data.avatarUrl)
if not StringUtils.IsNullOrEmpty(avatar)
result["authorThumbnails"] = [{ url: avatar, width: 88, height: 88 }, { url: avatar, width: 176, height: 176 }]
end if
return result
end function
function ChannelTabFromPiped(data as object) as object
' Piped /channel/{id}?tabs=x or /nextpage/channel/{id} -> Invidious channel tab feed
videos = VideosFromPiped(data.relatedStreams)
result = { videos: videos }
nextpage = ValidString(data.nextpage)
if nextpage <> ""
result["continuation"] = Base64Encode(nextpage)
end if
return result
end function
function ChannelPlaylistsFromPiped(data as object) as object
playlists = []
for each item in EnsureArray(data.relatedStreams)
if type(item) = "roAssociativeArray"
playlists.push({
"playlistId": ExtractPlaylistId(ValidString(item.url))
"title": ValidString(item.title)
"videoCount": ValidInt(item.videosCount)
"playlistThumbnail": ValidString(item.thumbnail)
"type": "playlist"
})
end if
end for
result = { playlists: playlists }
nextpage = ValidString(data.nextpage)
if nextpage <> ""
result["continuation"] = Base64Encode(nextpage)
end if
return result
end function
function PlaylistFromPiped(data as object, playlistId as string) as object
' Piped /playlists/{id} -> Invidious /api/v1/playlists/{plid}
videos = []
index = 0
for each item in EnsureArray(data.relatedStreams)
if type(item) = "roAssociativeArray"
videos.push(VideoFromPiped(item, index))
index += 1
end if
end for
result = {
"title": ValidString(data.name)
"playlistId": playlistId
"videoCount": ValidInt(data.videos)
"description": ValidString(data.description)
"author": ValidString(data.uploader)
"authorId": ExtractChannelId(ValidString(data.uploaderUrl))
"videos": videos
}
thumb = ValidString(data.thumbnailUrl)
if thumb <> ""
result["playlistThumbnail"] = thumb
end if
nextpage = ValidString(data.nextpage)
if nextpage <> ""
result["continuation"] = Base64Encode(nextpage)
end if
return result
end function
function SearchFromPiped(data as object) as object
' Piped /search -> Invidious /api/v1/search
items = EnsureArray(data.items)
videos = []
playlists = []
channels = []
for each item in items
t = ValidString(item.type)
if t = "stream" or t = "video" or t = "shortVideo"
videos.push(VideoFromPiped(item))
else if t = "playlist"
playlists.push({
"playlistId": ExtractPlaylistId(ValidString(item.url))
"title": ValidString(item.title)
"videoCount": ValidInt(item.videosCount)
"playlistThumbnail": ValidString(item.thumbnail)
"author": ValidString(item.uploaderName)
"type": "playlist"
})
else if t = "channel"
channels.push({
"authorId": ExtractChannelId(ValidString(item.url))
"author": ValidString(item.title)
"authorThumbnail": ValidString(item.avatar)
"authorThumbnails": [{ url: ValidString(item.avatar), width: 88, height: 88 }]
"description": ValidString(item.description)
"subCount": ValidInt(item.subscribers)
"handle": ValidString(item.handle)
"verified": item.verified = true
"type": "channel"
})
end if
end for
' VideoRowList consumes result.items; interleave converted entries in
' relevance order (videos first, then channels, then playlists).
merged = []
for each v in videos
merged.push(v)
end for
for each c in channels
merged.push(c)
end for
for each pl in playlists
merged.push(pl)
end for
result = {
"items": merged
"videos": videos
"playlists": playlists
"channels": channels
}
nextpage = ValidString(data.nextpage)
if nextpage <> ""
result["continuation"] = Base64Encode(nextpage)
end if
return result
end function
function VideoMetadataFromPiped(data as object, videoId as string) as object
' Piped /streams/{id} -> Invidious /api/v1/videos/:id (plus Playlet's
' innertube-ish playback fields: adaptiveFormats/formatStreams/hlsUrl/captions)
meta = {
"videoId": videoId
"title": ValidString(data.title)
"author": ValidString(data.uploader)
"authorId": ExtractChannelId(ValidString(data.uploaderUrl))
"lengthSeconds": ValidInt(data.duration)
"viewCount": ValidInt(data.views)
"published": MillisToSeconds(data.uploaded)
"description": ValidString(data.description)
"genre": EnsureArray(data.tags)
"videoThumbnails": ThumbnailsFromProxy(ValidString(data.thumbnailUrl), videoId)
"adaptiveFormats": []
"formatStreams": []
"captions": []
"relatedVideos": VideosFromPiped(data.relatedStreams)
"recommendedVideos": VideosFromPiped(data.relatedStreams)
"storyboards": []
"type": "video"
' Mark as our own parser shape so nothing tries innertube-only paths
"parser": "piped"
' Piped proxies signed googlevideo URLs already; Playlet can use them directly
"hlsUrl": ValidString(data.hls)
"dashUrl": ValidString(data.dash)
}
avatar = ValidString(data.uploaderAvatar)
if avatar <> ""
meta["authorThumbnails"] = [{ url: avatar, width: 88, height: 88 }]
end if
if data.livestream = true
meta["liveNow"] = true
end if
' Stream selection: prefer the HLS master (Piped's `hls` - AVC + fMP4
' up to 1080p, handled by Playlet's HlsRouter: segment rewriting,
' storyboards, quality filter, optional proxying). Only fall back to
' muxed progressive mp4 when there is no HLS master at all.
' adaptiveFormats stays empty on purpose: Piped reports fMP4 byte
' ranges (initStart/indexStart ints), not the init/index URLs that
' Playlet's DASH generator expects.
if StringUtils.IsNullOrEmpty(ValidString(data.hls))
for each stream in EnsureArray(data.videoStreams)
if type(stream) <> "roAssociativeArray"
continue for
end if
if stream.videoOnly = false and stream.format = "MP4"
meta.formatStreams.push(MuxedFromPiped(stream))
end if
end for
end if
for each caption in EnsureArray(data.subtitles)
if type(caption) <> "roAssociativeArray"
continue for
end if
url = ValidString(caption.url)
if url.StartsWith("//")
url = "https:" + url
end if
label = ValidString(caption.name)
if label = ""
label = ValidString(caption.code)
end if
meta.captions.push({
"url": url
language_code: ValidString(caption.code)
"label": label
auto_generated: caption.autoGenerated = true
})
end for
' Piped previewFrames -> Playlet's storyboard shape (see
' Innertube PlayerEndpoint.ParseStoryboards): templateUrl/width/height/
' count/interval/storyboardWidth/storyboardHeight/storyboardCount.
for each pf in EnsureArray(data.previewFrames)
if type(pf) <> "roAssociativeArray"
continue for
end if
urls = EnsureArray(pf.urls)
if urls.Count() > 0
frameW = ValidInt(pf.frameWidth)
frameH = ValidInt(pf.frameHeight)
cols = ValidInt(pf.framesPerPageX)
rows = ValidInt(pf.framesPerPageY)
total = ValidInt(pf.totalCount)
interval = ValidInt(pf.durationPerFrame)
perImage = cols * rows
imagesCount = 0
if perImage > 0
imagesCount = total \ perImage
if total mod perImage > 0
imagesCount += 1
end if
end if
' Playlet's storyboard manifest substitutes $M with the page
' index; Piped hands us the first page as ".../M0.jpg".
templateUrl = ValidString(urls[0])
if templateUrl.InStr("M0.") > 0
templateUrl = templateUrl.Replace("M0.", "$M.")
end if
meta.storyboards.push({
"templateUrl": templateUrl
"width": frameW
"height": frameH
"count": total
"interval": interval
"storyboardWidth": cols
"storyboardHeight": rows
"storyboardCount": imagesCount
})
end if
end for
return meta
end function
function FormatFromPiped(stream as object) as object
codec = CodecId(ValidString(stream.codec))
mime = ValidString(stream.mimeType)
container = ContainerFromMime(mime)
isVideo = ValidInt(stream.height) > 0
format = {
"url": ValidString(stream.url)
"itag": ValidInt(stream.itag)
"container": container
"codec": codec
mime_type: mime
"bitrate": ValidInt(stream.bitrate)
"contentLength": ValidInt(stream.contentLength)
"quality": QualityLabel(stream.quality)
"qualityLabel": QualityLabel(stream.quality)
"fps": ValidInt(stream.fps)
"width": ValidInt(stream.width)
"height": ValidInt(stream.height)
"init": ""
"index": ""
"approxDurationMs": ""
"audioSampleRate": ""
"aspectRatio": ""
"projectionType": ""
"averageBitrate": ValidInt(stream.bitrate)
}
if isVideo
format["type"] = `video; codecs="` + codec + `"`
else
format["type"] = `audio; codecs="` + codec + `"`
end if
' fMP4 segment ranges (Piped exposes them; Invidious uses init/index URLs).
' YouTube googlevideo URLs support #offset syntax via initStart/initEnd params,
' but Playlet's DASH generator only needs init/index to be present or absent
' consistently: absent means "progressive bytes with byte ranges".
return format
end function
function MuxedFromPiped(stream as object) as object
format = FormatFromPiped(stream)
format["quality"] = QualityLabel(stream.quality)
return format
end function
function CommentsFromPiped(data as object) as object
' Piped /comments/{id} -> Invidious /api/v1/comments/:id
comments = []
for each item in EnsureArray(data.comments)
if type(item) <> "roAssociativeArray"
continue for
end if
comment = {
"content": ValidString(item.commentText)
"author": ValidString(item.author)
"id": ValidString(item.commentId)
"published": ValidString(item.commentedTime)
"publishedText": ValidString(item.commentedTime)
"likeCount": ValidInt(item.likeCount)
"isPinned": item.pinned = true
"authorThumbnails": [{ url: ValidString(item.thumbnail), width: 88, height: 88 }]
"commentorUrl": ValidString(item.commentorUrl)
}
if item.hearted = true
comment["heart"] = true
end if
if item.creatorReplied = true
comment["creatorReplied"] = true
end if
if ValidInt(item.replyCount) > 0
replies = {
"replyCount": ValidInt(item.replyCount)
}
rp = ValidString(item.repliesPage)
if rp <> ""
replies["continuation"] = Base64Encode(rp)
end if
comment["replies"] = replies
end if
comments.push(comment)
end for
result = {
"commentCount": ValidInt(data.commentCount)
"comments": comments
"internalContinuation": ""
}
np = ValidString(data.nextpage)
if np <> ""
result["continuation"] = Base64Encode(np)
end if
return result
end function
' ---------------- helpers ----------------
function ExtractVideoId(url as string) as string
if url.InStr("v=") > 0
id = url.Mid(url.InStr("v=") + 2)
amp = id.InStr("&")
if amp > 0
id = id.Left(amp - 1)
end if
if id.Len() >= 11
return id.Left(11)
end if
end if
return ""
end function
function ExtractPlaylistId(url as string) as string
if url.InStr("list=") > 0
id = url.Mid(url.InStr("list=") + 5)
amp = id.InStr("&")
if amp > 0
id = id.Left(amp - 1)
end if
return id
end if
return ""
end function
function ExtractChannelId(url as string) as string
if url.InStr("/channel/") > 0
id = url.Mid(url.InStr("/channel/") + 9)
q = id.InStr("?")
if q > 0
id = id.Left(q - 1)
end if
return id
end if
if url.InStr("/c/") > 0
return url.Mid(url.InStr("/c/") + 3)
end if
if url.InStr("/user/") > 0
return url.Mid(url.InStr("/user/") + 6)
end if
return ""
end function
function ThumbnailsFromProxy(url as string, videoId as string) as object
thumbs = []
if not StringUtils.IsNullOrEmpty(url)
thumbs.push({ url: url, width: 320, height: 180, quality: "medium" })
thumbs.push({ url: url, width: 720, height: 404, quality: "high" })
thumbs.push({ url: url, width: 1280, height: 720, quality: "maxresdefault" })
end if
if thumbs.Count() = 0 and not StringUtils.IsNullOrEmpty(videoId)
thumbs.push({ url: `https://i.ytimg.com/vi/${videoId}/mqdefault.jpg`, width: 320, height: 180, quality: "medium" })
end if
return thumbs
end function
function ContainerFromMime(mime as string) as string
mime = LCase(mime)
if mime.InStr("mp4") > 0
return "mp4"
end if
if mime.InStr("webm") > 0
return "webm"
end if
if mime.InStr("3gpp") > 0 or mime.InStr("3gp") > 0
return "3gp"
end if
return ""
end function
function CodecId(codec as string) as string
' Piped gives "vp9", "av01.0.05M.08", "avc1.4d001f", "opus", "mp4a.40.2"
c = LCase(codec)
if c = "opus"
return "opus"
end if
if c = "vorbis"
return "vorbis"
end if
if c.startsWith("mp4a")
return c
end if
if c.startsWith("avc1") or c.startsWith("av01") or c.startsWith("vp8") or c.startsWith("vp9")
return c
end if
if c = "h264"
return "avc1.4d001f"
end if
if c = "av1"
return "av01.0.05M.08"
end if
if c = ""
return "vp9"
end if
return c
end function
function QualityLabel(quality as dynamic) as string
q = UCase(ValidString(quality))
if q = ""
return "unknown"
end if
if q = "LBRY"
return "unknown"
end if
if q.Right(1) <> "P"
return q + "p"
end if
return LCase(q)
end function
function MillisToSeconds(millis as dynamic) as integer
' NOTE: on this device CDbl() of a boxed roLongInt behaves like a
' SINGLE-precision float: 1256453853000 -> truncates to low 32 bits,
' then rounds (2323402568 -> 2323402624 -> negative int). So never
' convert the full epoch-millis to float; do string arithmetic:
' seconds = int(str[:-3]) when the value looks like epoch millis,
' keeping every intermediate inside int32.
if millis = invalid
return 0
end if
s = ""
if getInterface(millis, "ifString") <> invalid
s = ValidString(millis)
else if getInterface(millis, "ifToStr") <> invalid
' boxed roInt/roLongInt/roDouble from roJSONParser: CDbl() on a
' roLongInt silently truncates to 32 bits on this firmware, so
' go through the decimal string instead
s = millis.ToStr()
else
return 0
end if
s = s.Replace(" ", "")
' strip sign/decimals
if Left(s, 1) = "-"
s = s.Mid(2)
end if
dotIdx = InStr(s, ".")
if dotIdx > 0
s = s.Left(dotIdx - 1)
end if
if s = "" or s.Len() > 19
return 0
end if
for each c in s
if c < "0" or c > "9"
return 0
end if
end for
' epoch millis are 13 digits (2001-2286); 12 digits start 2001 too.
if s.Len() >= 12
' dropping the last 3 digits of epoch-millis yields epoch-seconds
' directly, and that value fits int32 until 2038
return Val(s.Left(s.Len() - 3))
end if
' already seconds (10 digits) or smaller
if s.Len() = 10
return Val(s)
end if
value = Val(s)
if value > 1000000000
return value
end if
return value / 1000
end function
function EnsureArray(value as dynamic) as object
if IsArray(value)
return value
end if
return []
end function
function Base64Encode(text as string) as string
bytes = CreateObject("roByteArray")
bytes.FromAsciiString(text)
return bytes.ToBase64String()
end function
function Base64Decode(text as string) as string
bytes = CreateObject("roByteArray")
bytes.FromBase64String(text)
return bytes.ToAsciiString()
end function
' ---------------- auth/profile token shapes ----------------
' Playlet stores invidious profile tokens as signed JSON and validates the
' scopes array + expire field client-side (VerifyTokenScope /
' DeriveAuthState). Piped's credential is a bare session UUID, so we wrap
' it in the same JSON shape here; the TV-side router unwraps it again
' before talking to Piped. The client only ever sends this blob to the
' local router, never to Piped itself.
function MakePipedTokenJson(username as string, sessionUuid as string, instance as string) as string
nowSeconds = TimeUtils.Now().AsSeconds()
expire = nowSeconds + 60 * 60 * 24 * 365 * 2
token = {
"token": sessionUuid
"user": ValidString(username)
"scopes": ["GET:feed", "GET:playlists*", "POST:tokens/*", ":history*", ":subscriptions*"]
"expire": expire
"lastUsed": nowSeconds * 1000
"createdAt": nowSeconds * 1000
}
return FormatJson(token)
end function
' Accepts either the wrapped JSON or a bare UUID (defensive: manual seeding).
function ExtractPipedSession(accessToken as dynamic) as string
token = StringUtils.ParseJsonSafe(ValidString(accessToken))
if IsAssociativeArray(token) and not StringUtils.IsNullOrEmpty(ValidString(token.token))
return ValidString(token.token)
end if
s = ValidString(accessToken)
if not StringUtils.IsNullOrEmpty(s) and InStr(s, "{") = 0
return s
end if
return ""
end function
function ExtractPipedUsername(accessToken as dynamic) as string
token = StringUtils.ParseJsonSafe(ValidString(accessToken))
if IsAssociativeArray(token)
return ValidString(token.user)
end if
return ""
end function
' Piped /subscriptions item {url:/channel/UC.., name, avatar, verified}
' -> Invidious subscription {author, authorId, url, avatarURL, ...}
function SubscriptionsFromPiped(list as dynamic) as object
out = []
for each item in EnsureArray(list)
if not IsAssociativeArray(item)
continue for
end if
channelId = ExtractChannelId(ValidString(item.url))
out.push({
"author": ValidString(item.name)
"authorId": channelId
"url": `/api/v1/channels/${channelId}`
"avatarURL": ValidString(item.avatar)
"notifications": false
"playlistID": ""
})
end for
return out
end function
' Piped /user/playlists item {id, name, thumbnail, videos?, updated?}
' -> Invidious playlist list item
function AuthPlaylistsFromPiped(list as dynamic) as object
out = []
for each item in EnsureArray(list)
if not IsAssociativeArray(item)
continue for
end if
updated = ValidInt(item.updated)
out.push({
"id": ValidString(item.id)
"type": "invidiousPlaylist"
"title": ValidString(item.name)
"url": `/playlist?list=${ValidString(item.id)}`
"author": ""
"authorId": ""
"description": ValidString(item.shortDescription)
"thumbnail": ValidString(item.thumbnail)
"videos": ValidInt(item.videos)
"updated": updated
"viewCount": 0
})
end for
return out
end function
end namespace
@@ -264,6 +264,9 @@ function ResolveBackendId(backend as string, service as Invidious.InvidiousServi
if backend = "playlet"
return "playlet"
end if
if backend = "piped"
return "piped"
end if
if service.GetInstance() = Invidious.PLAYLET_BUILT_IN_INSTANCE
return "built-in"
end if
@@ -41,6 +41,12 @@ namespace Http
hlsManifest = hlsResponse.Text()
' Some backends (Piped) return master manifests with relative
' variant URIs; since we serve the manifest from 127.0.0.1, the
' player would resolve them against the local server and 404.
' Make them absolute against the original manifest URL.
hlsManifest = m.MakeRelativeUrisAbsolute(hlsManifest, url)
hlsManifest = m.PrependManifestHeader(hlsManifest, v, url)
qualityFilter = m.CreateQualityFilter(quality)
@@ -253,6 +259,54 @@ ${storyboard.templateUrl.replace("$M", `${i}`)}
return hlsManifest
end function
function MakeRelativeUrisAbsolute(manifest as string, baseUrl as string) as string
if manifest = invalid or manifest = "" or baseUrl = invalid or baseUrl = ""
return manifest
end if
parsedUrl = UrlUtils.ParseUrl(baseUrl)
if parsedUrl = invalid or parsedUrl.host = invalid
return manifest
end if
protocol = parsedUrl.protocol
if protocol = invalid or protocol = ""
protocol = "https"
end if
origin = protocol + "://" + parsedUrl.host
if parsedUrl.port <> invalid and parsedUrl.port <> "" and parsedUrl.port <> "80" and parsedUrl.port <> "443"
origin = origin + ":" + parsedUrl.port
end if
' normalize line endings (CR-only manifests would be one line)
manifest = manifest.Replace(chr(13) + chr(10), chr(10))
manifest = manifest.Replace(chr(13), chr(10))
lines = manifest.Split(chr(10))
for i = 0 to lines.Count() - 1
line = lines[i]
trimmed = line.Trim()
if Left(trimmed, 1) = "/"
' bare relative URI line (variant/media playlist)
lines[i] = origin + trimmed
else if Left(trimmed, 1) = "#" and InStr(UCase(trimmed), "URI=" + chr(34) + "/") > 0
' attribute form: #EXT-X-MEDIA:...URI="/..." etc.
' split on double quotes; rewrite any segment that starts
' with a bare slash. no index math needed.
parts = trimmed.Split(chr(34))
for p = 0 to parts.Count() - 1
if Left(parts[p], 1) = "/"
parts[p] = origin + parts[p]
end if
end for
lines[i] = parts.Join(chr(34))
end if
end for
return lines.Join(chr(10))
end function
function GetPlayerMetadata() as object
player = m.videoQueue.player
@@ -0,0 +1,756 @@
import "pkg:/components/Services/Piped/PipedToInvidious.bs"
import "pkg:/components/Services/Invidious/InvidiousService.bs"
import "pkg:/source/services/HttpClient.bs"
import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/Types.bs"
import "pkg:/source/utils/UrlUtils.bs"
import "pkg:/source/utils/Logging.bs"
import "pkg:/components/Web/WebServer/Http/HttpRouter.bs"
' Serves the Invidious /api/v1 JSON shapes that Playlet's client expects,
' translated from a real Piped instance (https://github.com/TeamPiped/Piped).
' Mounted on Playlet's local web server, the client talks to:
' http://127.0.0.1:8888/playlet-piped-backend/api/v1/...
' and this router fetches:
' {piped.instance}/trending, /search, /streams/{id}, /channel/{id}, ...
' (Piped serves its REST API at the instance root, no /api/v1 prefix.)
namespace Http
class PipedBackendRouter extends HttpRouter
function new(server as object)
super()
m.preferences = server.sceneNodes.preferences
end function
function GetBaseUrl() as string
instance = ValidString(m.preferences["piped.instance"])
if StringUtils.IsNullOrEmpty(instance)
instance = "https://api.piped.spaghet.io"
end if
if instance.Right(1) = "/"
instance = instance.Left(instance.Len() - 1)
end if
v1 = instance.InStr("/api/v1")
if v1 > 0
instance = instance.Left(v1)
end if
return instance
end function
' GET /playlet-piped-backend/api/v1/manifest?url=<piped hls master>
' Fetches the Piped HLS master and rewrites its relative variant and
' media URIs to absolute proxy URLs, so Playlet's /api/hls proxy and
' the Roku player resolve them against the Piped instance, not 127.0.0.1.
function GetRewrittenHlsManifest(context as object) as boolean
request = context.request
response = context.response
url = request.query.url
if StringUtils.IsNullOrEmpty(url)
response.Default(400, "Missing url")
return true
end if
hlsResponse = HttpClient.Get(url).Await()
if not hlsResponse.IsSuccess()
LogWarn("Piped backend: manifest fetch failed", url, hlsResponse.StatusCode())
response.Redirect(url)
return true
end if
manifest = m.MakeRelativeUrisAbsolute(hlsResponse.Text(), url)
response.http_code = 200
response.headers["Content-Type"] = "application/x-mpegURL"
response.headers["Cache-Control"] = "no-cache, must-revalidate"
response.SetBodyDataString(manifest)
return true
end function
function MakeRelativeUrisAbsolute(manifest as string, baseUrl as string) as string
if manifest = invalid or manifest = "" or baseUrl = invalid or baseUrl = ""
return manifest
end if
parsedUrl = UrlUtils.ParseUrl(baseUrl)
if parsedUrl = invalid or parsedUrl.host = invalid
return manifest
end if
protocol = ValidString(parsedUrl.protocol)
if protocol = ""
protocol = "https"
end if
origin = protocol + "://" + parsedUrl.host
port = ValidString(parsedUrl.port)
if port <> "" and port <> "80" and port <> "443"
origin = origin + ":" + port
end if
bareCount = 0
attrCount = 0
' normalize line endings: some hosts serve manifests with CR-only
' line terminators, which Split("\n") would leave as one line
manifest = manifest.Replace(chr(13) + chr(10), chr(10))
manifest = manifest.Replace(chr(13), chr(10))
lines = manifest.Split(chr(10))
for i = 0 to lines.Count() - 1
trimmed = lines[i].Trim()
if Left(trimmed, 1) = "/"
' bare relative URI line (variant/media playlist)
lines[i] = origin + trimmed
bareCount = bareCount + 1
else if Left(trimmed, 1) = "#" and InStr(UCase(trimmed), "URI=" + chr(34) + "/") > 0
' attribute form: #EXT-X-MEDIA:...URI="/..." etc.
parts = trimmed.Split(chr(34))
for q = 0 to parts.Count() - 1
if Left(parts[q], 1) = "/"
parts[q] = origin + parts[q]
end if
end for
lines[i] = parts.Join(chr(34))
attrCount = attrCount + 1
end if
end for
result = lines.Join("\n")
return result
end function
function AuthLogSnapshot() as object
if m.authLog = invalid
return []
end if
return m.authLog
end function
function LibBuildTag() as string
return "PIPED-LIB-24"
end function
function FetchJson(path as string, params = invalid as object) as dynamic
url = m.GetBaseUrl() + path
request = HttpClient.Get(url)
if params <> invalid
for each key in params
value = params[key]
if value <> invalid and value <> ""
request.QueryParam(key, value)
end if
end for
end if
response = request.Await()
if not response.IsSuccess()
LogWarn("Piped backend: failed", path, response.StatusCode(), response.ErrorMessage())
return invalid
end if
return response.Json()
end function
function SendJson(response as object, body as object, httpCode = 200 as integer) as void
response.Json(body)
if httpCode <> 200
response.http_code = httpCode
end if
end function
function SendError(response as object, message as string) as void
m.SendJson(response, { error: message }, 500)
end function
' ---------------- GET dispatch ----------------
@get("*")
function GetAll(context as object) as boolean
route = context.request.route
prefix = "/playlet-piped-backend/api/v1/"
if not route.StartsWith(prefix)
return false
end if
tail = route.Mid(prefix.Len())
q = tail.InStr("?")
if q > 0
tail = tail.Left(q - 1)
end if
parts = tail.Split("/")
head = ""
if parts.Count() > 0
head = parts[0]
end if
if tail = "manifest"
return m.GetRewrittenHlsManifest(context)
else if head = "stats"
return m.GetStats(context)
else if head = "trending"
return m.GetTrending(context)
else if head = "popular"
' Piped has no "popular" feed; trending is the closest match
return m.GetTrending(context)
else if tail = "search/suggestions"
return m.GetSearchSuggestions(context)
else if head = "search"
return m.GetSearch(context)
else if head = "videos" and parts.Count() >= 2
context.videoId = parts[1]
return m.GetVideo(context)
else if head = "comments" and parts.Count() >= 2
context.videoId = parts[1]
return m.GetComments(context)
else if head = "channels" and parts.Count() >= 2
context.channelId = parts[1]
return m.GetChannel(context)
else if head = "playlists" and parts.Count() >= 2
context.playlistId = parts[1]
return m.GetPlaylist(context)
else if head = "auth"
return m.GetAuth(context)
end if
return false
end function
' ---------------- POST/DELETE dispatch (auth) ----------------
@post("*")
function PostAll(context as object) as boolean
if context.request.route.StartsWith("/playlet-piped-backend/api/v1/auth/")
return m.PostAuth(context)
end if
return false
end function
@delete("*")
function DeleteAll(context as object) as boolean
if context.request.route.StartsWith("/playlet-piped-backend/api/v1/auth/")
return m.DeleteAuth(context)
end if
return false
end function
' ---------------- auth: token plumbing ----------------
' The client sends the profile accessToken as our wrapped JSON
' (PipedToInvidious.MakePipedTokenJson); Piped itself wants the bare
' session UUID in a raw Authorization header (no Bearer prefix -
' verified against api.piped.spaghet.io), or ?authToken= for /feed.
function GetAccessToken(request as object) as dynamic
header = ValidString(request.headers["Authorization"])
if StringUtils.IsNullOrEmpty(header)
header = ValidString(request.headers["authorization"])
end if
if StringUtils.IsNullOrEmpty(header)
return invalid
end if
if header.StartsWith("Bearer ")
header = header.Mid(7)
end if
session = PipedToInvidious.ExtractPipedSession(header)
if StringUtils.IsNullOrEmpty(session)
return invalid
end if
return session
end function
function RequireAccessToken(context as object) as dynamic
request = context.request
response = context.response
token = m.GetAccessToken(request)
m.LogAuthRequest(request.route, "tok-" + Left(ValidString(token), 9))
if token = invalid
m.LogAuthRequest(request.route, "403-no-token")
response.Json({ "error": Invidious.ERROR_NOT_AUTHENTICATED })
response.http_code = 403
end if
return token
end function
' rolling window of auth calls for field debugging (exposed via stats)
function LogAuthRequest(route as string, outcome as string) as void
if m.authLog = invalid
m.authLog = []
end if
m.authLog.push(ValidString(route) + " => " + outcome)
if m.authLog.Count() > 12
trimmed = []
for t = m.authLog.Count() - 12 to m.authLog.Count() - 1
trimmed.push(m.authLog[t])
end for
m.authLog = trimmed
end if
end function
function PipedAuthGet(path as string, session as dynamic, params = invalid as object) as dynamic
request = HttpClient.Get(m.GetBaseUrl() + path)
if session <> invalid
if path = "/feed"
request.QueryParam("authToken", session)
else
request.Header("Authorization", session)
end if
end if
' Piped's ThrottlingCache keys on path+query and replays cached
' error responses (re-seeding them on every hit), so one genuine
' 401 - e.g. right after the broker rotates a session - poisons
' this exact URL for the TV for as long as it keeps polling. A
' per-call nonce makes every authenticated upstream GET a fresh
' key and a real lookup; the fork's handlers ignore unknown params.
request.QueryParam("pb", CreateObject("roDeviceInfo").GetRandomUUID())
if params <> invalid
for each key in params
value = params[key]
if value <> invalid and value <> ""
request.QueryParam(key, value)
end if
end for
end if
return request.Await()
end function
function PipedAuthPost(path as string, body as object, session as dynamic) as dynamic
request = HttpClient.Post(m.GetBaseUrl() + path)
request.Header("Content-Type", "application/json")
if session <> invalid
request.Header("Authorization", session)
end if
request.JsonBody(body)
return request.Await()
end function
' ---------------- auth handlers ----------------
' GET /api/v1/auth/<what>
function GetAuth(context as object) as boolean
route = context.request.route
tail = route.Mid("/playlet-piped-backend/api/v1/auth/".Len())
parts = tail.Split("/")
head = ""
if parts.Count() > 0
head = parts[0]
end if
if head = "feed"
return m.GetAuthFeed(context)
else if head = "subscriptions"
return m.GetAuthSubscriptions(context)
else if head = "playlists"
if parts.Count() >= 2
context.playlistId = parts[1]
return m.GetAuthPlaylist(context)
end if
return m.GetAuthPlaylists(context)
else if head = "history"
' Piped (this fork) has no server-side watch history; the
' browser keeps it in IndexedDB. Return empty, not an error.
m.SendJson(context.response, { "items": [], "continuation": "" })
return true
end if
return m.UnsupportedAuth(context)
end function
' POST /api/v1/auth/history (mark watched) + /auth/subscriptions/<id> (subscribe)
function PostAuth(context as object) as boolean
route = context.request.route
tail = route.Mid("/playlet-piped-backend/api/v1/auth/".Len())
session = m.RequireAccessToken(context)
if session = invalid
return true
end if
if tail = "history" or Left(tail, 8) = "history/"
' no server-side history on this Piped fork: accept silently
m.SendJson(context.response, { "status": "ok" })
return true
end if
if tail = "subscriptions" or Left(tail, 14) = "subscriptions/"
' Playlet's Subscribe posts to /auth/subscriptions/<channelId>
channelId = ""
if tail.Len() > 14
channelId = tail.Mid(14)
end if
if StringUtils.IsNullOrEmpty(channelId)
m.SendJson(context.response, { "error": "Missing channelId" }, 400)
return true
end if
res = m.PipedAuthPost("/subscribe", { channelId: channelId }, session)
if not res.IsSuccess()
LogWarn("Piped backend: subscribe failed", res.StatusCode())
m.SendJson(context.response, { "error": "Subscribe failed" }, 502)
return true
end if
m.SendJson(context.response, { "status": "ok" })
return true
end if
' tokens/register etc. - accept, Piped sessions need no registration
m.SendJson(context.response, { "status": "ok" })
return true
end function
' DELETE /api/v1/auth/subscriptions/<channelId>
function DeleteAuth(context as object) as boolean
route = context.request.route
tail = route.Mid("/playlet-piped-backend/api/v1/auth/".Len())
session = m.RequireAccessToken(context)
if session = invalid
return true
end if
if Left(tail, 14) = "subscriptions/"
channelId = tail.Mid(14)
res = m.PipedAuthPost("/unsubscribe", { channelId: channelId }, session)
if not res.IsSuccess()
LogWarn("Piped backend: unsubscribe failed", res.StatusCode())
m.SendJson(context.response, { "error": "Unsubscribe failed" }, 502)
return true
end if
m.SendJson(context.response, { "status": "ok" })
return true
end if
' logout/unregister: do NOT call Piped /logout - the same session
' is in use by the user's browser, and logging out would kill it.
m.SendJson(context.response, { "status": "ok" })
return true
end function
function GetAuthFeed(context as object) as boolean
session = m.RequireAccessToken(context)
if session = invalid
return true
end if
res = m.PipedAuthGet("/feed", session)
if not res.IsSuccess()
m.LogAuthRequest(context.request.route, `feed-upstream-${res.StatusCode()}`)
LogWarn("Piped backend: auth feed failed", res.StatusCode())
if m.IsSessionRejected(res, session)
m.SendSessionRejected(context.response)
else
m.SendJson(context.response, { "error": "Feed unavailable" }, 502)
end if
return true
end if
m.LogAuthRequest(context.request.route, "feed-ok")
items = PipedToInvidious.VideosFromPiped(res.Json())
m.SendJson(context.response, { "videos": items })
return true
end function
function GetAuthSubscriptions(context as object) as boolean
session = m.RequireAccessToken(context)
if session = invalid
return true
end if
res = m.PipedAuthGet("/subscriptions", session)
if not res.IsSuccess()
m.LogAuthRequest(context.request.route, `subs-upstream-${res.StatusCode()}`)
LogWarn("Piped backend: subscriptions failed", res.StatusCode())
if m.IsSessionRejected(res, session)
m.SendSessionRejected(context.response)
else
m.SendJson(context.response, { "error": "Subscriptions unavailable" }, 502)
end if
return true
end if
subsData = res.Json()
subsCount = 0
if IsArray(subsData)
subsCount = subsData.Count()
end if
m.LogAuthRequest(context.request.route, `subs-ok-${subsCount}`)
m.SendJson(context.response, PipedToInvidious.SubscriptionsFromPiped(res.Json()))
return true
end function
function GetAuthPlaylists(context as object) as boolean
session = m.RequireAccessToken(context)
if session = invalid
return true
end if
res = m.PipedAuthGet("/user/playlists", session)
if not res.IsSuccess()
m.LogAuthRequest(context.request.route, `playlists-upstream-${res.StatusCode()}`)
LogWarn("Piped backend: playlists failed", res.StatusCode())
if m.IsSessionRejected(res, session)
m.SendSessionRejected(context.response)
else
m.SendJson(context.response, { "error": "Playlists unavailable" }, 502)
end if
return true
end if
m.SendJson(context.response, PipedToInvidious.AuthPlaylistsFromPiped(res.Json()))
return true
end function
function GetAuthPlaylist(context as object) as boolean
session = m.RequireAccessToken(context)
if session = invalid
return true
end if
playlistId = ValidString(context.playlistId)
res = m.PipedAuthGet(`/playlists/${playlistId}`, session)
if not res.IsSuccess()
m.SendJson(context.response, { "error": "Playlist unavailable" }, 502)
return true
end if
m.SendJson(context.response, PipedToInvidious.PlaylistFromPiped(res.Json(), playlistId))
return true
end function
' Piped rejects a rotated/dead session with 401 "An invalid Session ID
' was provided." Playlet's MarkNeedsReauthIfCredentialsRejected only
' fires on a 403 whose body contains this exact Invidious phrasing,
' so translate: broker rotation then cleanly re-arms the TV login.
function SendSessionRejected(response as object) as void
response.Json({ "error": "Request must be authenticated" })
response.http_code = 403
end function
' Piped's ThrottlingCache replays error responses per path (and can
' answer a live session with a stale 401 for minutes), so a 401 here
' is NOT proof of death. Confirm against two independent endpoints;
' only if BOTH also reject is the session truly gone. When the picture
' stays ambiguous, callers get a 502 instead: the row shows "failed to
' load" and retries on the next refresh, but the stored profile - and
' its token - survive, instead of MarkNeedsReauth wiping a live login.
function IsSessionRejected(res as object, session as dynamic) as boolean
if res.StatusCode() <> 401 and not (res.StatusCode() = 400 and res.Text().InStr("session is a required parameter") > 0)
return false
end if
if session = invalid
return true
end if
probe1 = m.PipedAuthGet("/subscriptions", session)
m.LogAuthRequest("probe1", `subs-${probe1.StatusCode()}`)
if probe1.IsSuccess()
return false
end if
probe2 = m.PipedAuthGet("/user/playlists", session)
m.LogAuthRequest("probe2", `playlists-${probe2.StatusCode()}`)
if probe2.IsSuccess()
return false
end if
' Both probes rejected too - but they can replay throttle 401s as
' well. One last delay-and-retry on the primary probe distinguishes
' a throttle window (persists ~minutes) from... nothing; if the
' retry still 401s we accept the verdict and ask for re-login.
wait(3000, CreateObject("roMessagePort"))
probe3 = m.PipedAuthGet("/subscriptions", session)
m.LogAuthRequest("probe3", `subs-retry-${probe3.StatusCode()}`)
return not probe3.IsSuccess()
end function
function UnsupportedAuth(context as object) as boolean
m.SendJson(context.response, {
"error": "Piped backend accounts are not supported yet. Browse anonymously, or log in to your Piped instance in a browser."
}, 400)
return true
end function
' ---------------- handlers ----------------
function GetStats(context as object) as boolean
response = context.response
stats = m.FetchJson("/stats")
if not IsAssociativeArray(stats)
stats = {}
end if
m.SendJson(response, {
"buildTag": m.LibBuildTag()
"authLog": m.AuthLogSnapshot()
"software": "piped"
"version": ValidString(stats.version)
"userCount": ValidInt(stats.userCount)
"lastStreamed": ""
"videoCountPlaylists": 0
"videoCount": 0
"usage": {}
})
return true
end function
function GetTrending(context as object) as boolean
request = context.request
response = context.response
region = ValidString(request.query.region)
if StringUtils.IsNullOrEmpty(region)
region = "US"
end if
items = m.FetchJson("/trending", { region: region })
if not IsArray(items)
m.SendError(response, "Failed to get trending feed")
return true
end if
videos = PipedToInvidious.VideosFromPiped(items)
if videos.Count() = 0
m.SendError(response, "Failed to get trending feed")
return true
end if
' Invidious /api/v1/trending returns a bare array; DefaultHandler
' wraps it as {items: [...]}.
response.Json(videos)
return true
end function
function GetSearchSuggestions(context as object) as boolean
request = context.request
response = context.response
query = ValidString(request.query.q)
items = m.FetchJson("/suggestions", { query: query })
suggestions = []
if IsArray(items)
for each item in items
suggestions.push(ValidString(item))
end for
end if
m.SendJson(response, {
"suggestions": suggestions
"params": ""
})
return true
end function
function GetSearch(context as object) as boolean
request = context.request
response = context.response
query = ValidString(request.query.q)
continuation = ValidString(request.query.continuation)
if StringUtils.IsNullOrEmpty(continuation)
params = { q: query, filter: "all" }
page = ValidString(request.query.page)
if not StringUtils.IsNullOrEmpty(page)
params.page = page
end if
data = m.FetchJson("/search", params)
else
nextpage = PipedToInvidious.Base64Decode(continuation)
data = m.FetchJson("/nextpage/search", { q: query, filter: "all", nextpage: nextpage })
end if
if not IsAssociativeArray(data) or not IsArray(data.items)
m.SendError(response, "Failed to search: no results found")
return true
end if
m.SendJson(response, PipedToInvidious.SearchFromPiped(data))
return true
end function
function GetVideo(context as object) as boolean
response = context.response
data = m.FetchJson("/streams/" + context.videoId)
if not IsAssociativeArray(data) or StringUtils.IsNullOrEmpty(ValidString(data.title))
m.SendError(response, "Failed to get video info")
return true
end if
m.SendJson(response, PipedToInvidious.VideoMetadataFromPiped(data, ValidString(context.videoId)))
return true
end function
function GetComments(context as object) as boolean
request = context.request
response = context.response
videoId = ValidString(context.videoId)
continuation = ValidString(request.query.continuation)
if StringUtils.IsNullOrEmpty(continuation)
data = m.FetchJson("/comments/" + videoId)
else
nextpage = PipedToInvidious.Base64Decode(continuation)
data = m.FetchJson("/nextpage/comments/" + videoId, { nextpage: nextpage })
end if
if not IsAssociativeArray(data)
m.SendError(response, "Failed to get comments")
return true
end if
m.SendJson(response, PipedToInvidious.CommentsFromPiped(data))
return true
end function
function GetChannel(context as object) as boolean
request = context.request
response = context.response
channelId = ValidString(context.channelId)
continuation = ValidString(request.query.continuation)
if StringUtils.IsNullOrEmpty(continuation)
data = m.FetchJson("/channel/" + channelId)
else
nextpage = PipedToInvidious.Base64Decode(continuation)
data = m.FetchJson("/nextpage/channel/" + channelId, { nextpage: nextpage })
end if
if not IsAssociativeArray(data)
m.SendError(response, "Failed to get channel")
return true
end if
m.SendJson(response, PipedToInvidious.ChannelFromPiped(data, channelId))
return true
end function
function GetPlaylist(context as object) as boolean
request = context.request
response = context.response
playlistId = ValidString(context.playlistId)
params = {}
continuation = ValidString(request.query.continuation)
if not StringUtils.IsNullOrEmpty(continuation)
params.nextpage = PipedToInvidious.Base64Decode(continuation)
end if
data = m.FetchJson("/playlists/" + playlistId, params)
if not IsAssociativeArray(data) or StringUtils.IsNullOrEmpty(ValidString(data.name))
m.SendError(response, "Failed to get playlist")
return true
end if
m.SendJson(response, PipedToInvidious.PlaylistFromPiped(data, playlistId))
return true
end function
end class
end namespace
@@ -0,0 +1,526 @@
import "pkg:/components/Services/Piped/PipedToInvidious.bs"
import "pkg:/source/services/HttpClient.bs"
import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/Types.bs"
import "pkg:/source/utils/UrlUtils.bs"
import "pkg:/source/utils/Logging.bs"
import "pkg:/components/Web/WebServer/Http/HttpRouter.bs"
namespace Http
' Phone-side login page for the Piped backend, mirroring InvidiousRouter's
' QR login flow. Served on the TV's local web server:
' GET /piped/login -> HTML page (SSO link + user/pass form)
' POST /piped/login -> {username,password} form -> Piped /login
' GET /piped/login/sso -> 302 to the instance's SSO broker (?next=/sso-tv...)
' GET /piped/token_callback -> ?token=<uuid>&nonce=<n> -> stores profile
' GET /piped/login/status -> JSON {waiting, username} for polling
' The login dialog on the TV closes itself when currentProfileChanged fires;
' this router only needs to create the profile via profilesService.
class PipedLoginRouter extends HttpRouter
function new(server as object)
super()
m.server = server
m.profilesNode = server.sceneNodes.profilesService
m.preferences = server.sceneNodes.preferences
m.routes.push({ method: "GET", path: "/piped/login", router: m, func: "LoginPage" })
m.routes.push({ method: "POST", path: "/piped/login", router: m, func: "SubmitPassword" })
m.routes.push({ method: "GET", path: "/piped/login/sso", router: m, func: "RedirectToSso" })
m.routes.push({ method: "GET", path: "/piped/token_callback", router: m, func: "TokenCallback" })
m.routes.push({ method: "GET", path: "/piped/login/status", router: m, func: "LoginStatus" })
m.routes.push({ method: "GET", path: "/piped/login/debug", router: m, func: "DebugToken" })
m.routes.push({ method: "GET", path: "/piped/login/verify", router: m, func: "VerifyProbe" })
end function
' ---------------- shared ----------------
function Xml(text as string) as string
out = text.Replace("&", "&amp;")
out = out.Replace("<", "&lt;")
out = out.Replace(">", "&gt;")
out = out.Replace(chr(34), "&quot;")
return out
end function
function GetInstance() as string
return ValidString(m.preferences["piped.instance"])
end function
function GetTvBaseUrl() as dynamic
' m.server is the HttpServer class; its .task is the PlayletWebServer
' SGTask which owns GetServerAddress (DialRouter uses the same task).
if m.server.task = invalid
return invalid
end if
return m.server.task@.GetServerAddress()
end function
' A small rolling window of issued nonces: the page may be reloaded,
' the QR rescanned, or a second phone pointed at the same dialog. A
' single-slot nonce made any of those (or a health probe) race the
' real login out of existence.
' Every page request issues a fresh nonce and keeps the three most
' recent valid, so whichever link/QR the phone actually holds still
' works - and a cached page response can never hand out a stale,
' already-consumed nonce.
' Every page request issues a fresh nonce. Nonces live in a fixed
' 4-slot ring so no roArray resize methods (removeIdx/deleteIdx/
' subArray, which vary by firmware) are ever needed - only plain
' index assignment. The three most recent nonces stay valid, so a
' reloaded page, a rescanned QR, or a health probe can never race
' the real login out of existence; older ones fall out of the ring.
' The ring lives in the registry so an app restart (or a redeploy)
' mid-login cannot 403 a callback whose nonce was issued before it:
' the phone may sit on the SSO provider's page for minutes while the
' TV side churns. Load once, save on every mutation.
function LoadNonceRing() as void
if m.loginNonces <> invalid
return
end if
m.loginNonces = ["", "", "", ""]
m.loginNonceSlot = 0
reg = CreateObject("roRegistrySection", "piped_login")
if reg.Exists("nonces")
stored = reg.Read("nonces").Split("|")
slot = Val(ValidString(reg.Read("slot")))
if slot >= 0 and slot < 4
m.loginNonceSlot = slot
end if
for i = 0 to 3
if i < stored.Count() and stored[i] <> invalid
m.loginNonces[i] = ValidString(stored[i])
end if
end for
end if
end function
function SaveNonceRing() as void
reg = CreateObject("roRegistrySection", "piped_login")
reg.Write("nonces", m.loginNonces[0] + "|" + m.loginNonces[1] + "|" + m.loginNonces[2] + "|" + m.loginNonces[3])
reg.Write("slot", Str(m.loginNonceSlot).Replace(" ", ""))
reg.Flush()
end function
function ClearNonceRing() as void
m.loginNonces = ["", "", "", ""]
m.loginNonceSlot = 0
m.SaveNonceRing()
end function
function EnsureLoginNonce() as string
m.LoadNonceRing()
nonce = CreateObject("roDeviceInfo").GetRandomUUID()
m.loginNonces[m.loginNonceSlot] = nonce
m.loginNonceSlot = (m.loginNonceSlot + 1) mod 4
m.SaveNonceRing()
return nonce
end function
function KnownNonceIdx(nonce as string) as integer
m.LoadNonceRing()
if nonce = ""
return -1
end if
for i = 0 to 3
if m.loginNonces[i] = nonce
return i
end if
end for
return -1
end function
' Put a nonce into the ring (no-op if already present). The SSO
' redirect re-registers the nonce its URL carries so a login that
' started before an app restart - which wipes the in-memory ring -
' can still complete its callback instead of 403ing.
function RegisterNonce(nonce as string) as void
m.LoadNonceRing()
for i = 0 to 3
if m.loginNonces[i] = nonce
return
end if
end for
m.loginNonces[m.loginNonceSlot] = nonce
m.loginNonceSlot = (m.loginNonceSlot + 1) mod 4
end function
' The gate script appends token+nonce to the cb URL while the cb
' template already carries a nonce, so the callback can arrive with
' the key twice; Playlet's query parser turns duplicate keys into an
' ARRAY and ValidString(array) is "" -> the nonce looked unknown.
function FirstStr(v as dynamic) as string
if GetInterface(v, "ifArray") <> invalid
if v.Count() > 0
return ValidString(v[0])
end if
return ""
end if
return ValidString(v)
end function
function ReadLastSession() as string
reg = CreateObject("roRegistrySection", "piped_login")
if reg.Exists("current")
return reg.Read("current")
end if
return ""
end function
function WriteLastSession(sessionUuid as string) as void
reg = CreateObject("roRegistrySection", "piped_login")
reg.Write("current", sessionUuid)
reg.Flush()
end function
function SetLoggedInProfile(username as string, sessionUuid as string) as void
instance = m.GetInstance()
port = Str(m.server.task.port).Replace(" ", "")
serverUrl = "http://127.0.0.1:" + port + "/playlet-piped-backend"
tokenJson = PipedToInvidious.MakePipedTokenJson(username, sessionUuid, instance)
profile = CreateObject("roSGNode", "ProfileContentNode")
profile.type = "invidious"
profile.username = username
profile.accessToken = tokenJson
profile.serverUrl = serverUrl
m.profilesNode@.LoginWithProfile(profile)
m.loggedInUsername = username
end function
' ---------------- GET /piped/login ----------------
function LoginPage(context as object) as boolean
response = context.response
nonce = m.EnsureLoginNonce()
instance = m.GetInstance()
html = m.PageShell("Sign in to Piped", m.Body(instance, nonce))
response.http_code = 200
response.headers["Cache-Control"] = "no-store, max-age=0"
response.ContentType("text/html")
response.SetBodyDataString(html)
return true
end function
function Body(instance as string, nonce as string) as string
ssoLink = "/piped/login/sso?nonce=" + nonce
return `
<div class="card">
<h1>Piped</h1>
<p class="muted">Instance: ${m.Xml(instance)}</p>
<a class="btn primary" href="${ssoLink}">Sign in with SSO (Authentik)</a>
<div class="sep">or use a Piped account</div>
<form method="POST" action="/piped/login">
<input name="username" type="text" placeholder="username" autocomplete="username" required>
<input name="password" type="password" placeholder="password" autocomplete="current-password" required>
<input type="hidden" name="nonce" value="${nonce}">
<button class="btn" type="submit">Sign in</button>
</form>
<p class="muted small">This signs in the TV only. Your phone browser session is untouched. SSO accounts have no password; use the SSO button.</p>
</div>`
end function
' ---------------- GET /piped/login/sso ----------------
function RedirectToSso(context as object) as boolean
request = context.request
response = context.response
reqNonce = m.FirstStr(request.query.nonce)
if reqNonce <> ""
' The phone clicked the link the login page handed out; keep
' that nonce valid for the callback this redirect starts,
' even if the app restarted (ring wiped) in between.
nonce = reqNonce
m.RegisterNonce(reqNonce)
else
nonce = m.EnsureLoginNonce()
end if
instance = m.GetInstance()
if StringUtils.IsNullOrEmpty(instance)
response.Default(503, "Piped instance not configured")
return true
end if
tv = m.GetTvBaseUrl()
if tv = invalid
response.Default(503, "TV address not available")
return true
end if
callback = `${tv}/piped/token_callback?nonce=${nonce}`
' The SSO broker lives on the API origin (SSO_PUBLIC_ORIGIN) under /sso
broker = instance
if Right(broker, 1) = "/"
broker = broker.Left(broker.Len() - 1)
end if
' next must be a same-origin path on the Piped frontend; the gate
' script special-cases the /sso-tv path and bounces the phone here.
nextPath = "/sso-tv?cb=" + callback.EncodeUriComponent() + "&nonce=" + nonce.EncodeUriComponent()
ssoUrl = `${broker}/sso/?next=${nextPath.EncodeUriComponent()}`
response.Redirect(ssoUrl, 302)
return true
end function
' ---------------- POST /piped/login (username/password) ----------------
function SubmitPassword(context as object) as boolean
request = context.request
response = context.response
fields = m.ParseFormBody(ValidString(request.BodyText()))
username = ValidString(fields.username)
password = ValidString(fields.password)
nonce = m.FirstStr(fields.nonce)
if nonce <> "" and m.KnownNonceIdx(nonce) < 0
response.Default(400, m.ErrorPage(`Stale login page. <a href="/piped/login">Start again</a>`))
return true
end if
if StringUtils.IsNullOrEmpty(username) or StringUtils.IsNullOrEmpty(password)
response.Default(400, m.ErrorPage("Username and password are required."))
return true
end if
instance = m.GetInstance()
if StringUtils.IsNullOrEmpty(instance)
response.Default(503, m.ErrorPage("Piped instance not configured on the TV."))
return true
end if
body = FormatJson({ username: username, password: password })
httpRequest = HttpClient.Post(`${instance}/login`)
httpRequest.Header("Content-Type", "application/json")
res = httpRequest.TextBody(body).Await()
data = res.Json()
if not res.IsSuccess() or not IsAssociativeArray(data) or StringUtils.IsNullOrEmpty(ValidString(data.token))
detail = "Login failed."
if IsAssociativeArray(data) and not StringUtils.IsNullOrEmpty(ValidString(data.error))
detail = ValidString(data.error)
end if
response.http_code = 200
response.headers["Cache-Control"] = "no-store, max-age=0"
response.ContentType("text/html")
response.SetBodyDataString(m.ErrorPage(detail + " <a href='/piped/login'>Try again</a>"))
return true
end if
m.SetLoggedInProfile(username, ValidString(data.token))
response.http_code = 200
response.headers["Cache-Control"] = "no-store, max-age=0"
response.ContentType("text/html")
response.SetBodyDataString(m.PageShell("Signed in", m.SuccessBody(username)))
return true
end function
function ParseFormBody(form as string) as object
fields = {}
for each pair in form.Split("&")
eq = pair.InStr("=")
if eq <= 1
continue for
end if
key = pair.Left(eq - 1).DecodeUriComponent()
value = pair.Mid(eq + 1).DecodeUriComponent()
fields[key] = value
end for
return fields
end function
' ---------------- GET /piped/token_callback (SSO handoff) ----------------
function TokenCallback(context as object) as boolean
request = context.request
response = context.response
token = m.FirstStr(request.query.token)
nonce = m.FirstStr(request.query.nonce)
if StringUtils.IsNullOrEmpty(token)
response.Default(400, m.ErrorPage("Missing token."))
return true
end if
' Only accept a login this device handed out (a nonce from the
' rolling window above). Consume it so each link is single-use.
idx = m.KnownNonceIdx(nonce)
if idx < 0
' A consumed nonce arriving with the SAME session we just
' installed is a retry/replay of a login that already
' succeeded (the gate script can bounce the phone twice) -
' show success, not an error the user cannot act on.
if nonce <> "" and token = m.ReadLastSession()
response.http_code = 200
response.headers["Cache-Control"] = "no-store, max-age=0"
response.ContentType("text/html")
response.SetBodyDataString(m.PageShell("Signed in", m.SuccessBody(m.LookupUsername(token))))
return true
end if
response.Default(403, m.ErrorPage(`Login link expired or already used. <a href="/piped/login">Start again</a>`))
return true
end if
' consume: blank the slot (roArray splice ops vary by firmware)
m.loginNonces[idx] = ""
m.SaveNonceRing()
' Resolve the username for the session, best effort.
username = m.LookupUsername(token)
m.SetLoggedInProfile(username, token)
m.WriteLastSession(token)
response.http_code = 200
response.headers["Cache-Control"] = "no-store, max-age=0"
response.ContentType("text/html")
response.SetBodyDataString(m.PageShell("Signed in", m.SuccessBody(username)))
return true
end function
' The fork has no /user endpoint, but the authenticated RSS feed names
' the account: its <subtitle> is "Piped's RSS subscription feed for
' <username>.". Read the username from there; fall back to a stable
' uuid label if the shape ever changes. (The profile name is cosmetic.)
function LookupUsername(sessionUuid as string) as string
instance = m.GetInstance()
if StringUtils.IsNullOrEmpty(instance)
return "piped"
end if
' /feed/rss authenticates via ?authToken= (same contract as /feed).
' The pb nonce keeps this off Piped's ThrottlingCache replay keys.
nonce = CreateObject("roDeviceInfo").GetRandomUUID()
url = `${instance}/feed/rss?authToken=${sessionUuid}&pb=${nonce}`
res = HttpClient.Get(url).Await()
xml = ""
if res.IsSuccess()
xml = res.Text()
end if
if not StringUtils.IsNullOrEmpty(xml)
' Split instead of Mid/InStr: substring indexing disagreed with
' the docs on this firmware (both off-by-one directions shipped
' wrong results); Split boundaries are unambiguous.
marker = "feed for "
parts = xml.Split(marker)
if parts.Count() > 1
tail = ValidString(parts[1])
name = ValidString(tail.Split(".")[0])
if name.Len() > 0 and name.Len() < 25
return name
end if
end if
end if
return "piped-" + Left(sessionUuid, 8)
end function
' ---------------- GET /piped/login/status ----------------
function LoginStatus(context as object) as boolean
response = context.response
response.Json({
"waiting": m.loginNonces <> invalid and m.loginNonces.Count() > 0
"username": ValidString(m.loggedInUsername)
})
return true
end function
function DebugToken(context as object) as boolean
tj = PipedToInvidious.MakePipedTokenJson("u1", "abc-def", "https://api.piped.spaghet.io")
parsed = StringUtils.ParseJsonSafe(tj)
extracted = PipedToInvidious.ExtractPipedSession(tj)
context.response.http_code = 200
context.response.Json({
"tokenJsonType": type(tj)
"tokenJsonLen": Str(tj.Len())
"tokenJson": tj
"parsedOk": IsAssociativeArray(parsed)
"extracted": extracted
})
return true
end function
' Replays the two boot-time checks Playlet applies to a stored
' invidious profile token (DeriveAuthState + VerifyTokenScope) and
' reports each step, to find why a freshly stored Piped token gets
' marked NeedsReauth after an app restart.
function VerifyProbe(context as object) as boolean
response = context.response
profiles = m.profilesNode@.GetProfilesDto(true)
out = { "steps": [] }
for each profile in profiles.profiles
tok = ValidString(profile.accessToken)
s = {
"username": ValidString(profile.username)
"tokLen": Len(tok)
"tokHead": Left(tok, 40)
}
parsed = StringUtils.ParseJsonSafe(tok)
s["parsed"] = IsAssociativeArray(parsed)
if IsAssociativeArray(parsed)
scopes = parsed.scopes
s["scopesIsArray"] = IsArray(scopes)
if IsArray(scopes)
joined = scopes.Join(",")
s["scopesMatch"] = (joined = "GET:feed,GET:playlists*,POST:tokens/*,:history*,:subscriptions*")
s["scopesJoined"] = joined
end if
s["expireType"] = type(parsed.expire)
s["expireIsNumber"] = IsNumber(parsed.expire)
nowS = TimeUtils.Now().AsSeconds()
s["expireVal"] = Str(parsed.expire)
s["nowVal"] = Str(nowS)
s["expired"] = (IsNumber(parsed.expire) and parsed.expire <= nowS)
end if
out.steps.push(s)
end for
response.http_code = 200
response.Json(out)
return true
end function
' ---------------- HTML ----------------
function PageShell(title as string, body as string) as string
return `<!doctype html><html lang="en"><head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>${m.Xml(title)} - Piped on TV</title>
<style>
body{font:16px/1.5 system-ui,-apple-system,Segoe UI,Roboto,sans-serif;background:#0f1115;color:#e6e8eb;display:flex;min-height:100vh;align-items:center;justify-content:center;margin:0;padding:16px}
.card{width:min(420px,100%);background:#171a21;border:1px solid #262b36;border-radius:14px;padding:28px;text-align:center}
h1{margin:0 0 4px;font-size:1.4rem;color:#38bdf8}
.muted{color:#98a2b3}.small{font-size:.85rem}
.btn{display:block;width:100%;box-sizing:border-box;margin:10px 0;padding:12px;border-radius:10px;border:1px solid #3b4353;background:#232833;color:#e6e8eb;font-size:1rem;text-decoration:none;cursor:pointer}
.btn.primary{background:#0ea5e9;border-color:#0ea5e9;color:#04121d;font-weight:600}
input{display:block;width:100%;box-sizing:border-box;margin:10px 0;padding:12px;border-radius:10px;border:1px solid #3b4353;background:#0f1115;color:#e6e8eb;font-size:1rem}
.sep{color:#67707f;font-size:.85rem;margin:18px 0 4px;text-transform:uppercase;letter-spacing:.06em}
.ok{font-size:2.2rem;color:#34d399;margin:0}
a{color:#38bdf8}
</style></head><body>${body}</body></html>`
end function
function SuccessBody(username as string) as string
return `
<div class="card">
<p class="ok">&#10003;</p>
<h1>Signed in to the TV</h1>
<p class="muted">Account: ${m.Xml(username)}</p>
<p class="muted small">You can close this page and grab the remote. The Piped app on your TV now has your subscriptions, playlists and recommended feed.</p>
</div>`
end function
function ErrorPage(message as string) as string
return `<div class="card"><h1>Not signed in</h1><p>${message}</p></div>`
end function
end class
end namespace
@@ -8,6 +8,8 @@ import "pkg:/components/Web/PlayletWebServer/Middleware/HomeRouter.bs"
import "pkg:/components/Web/PlayletWebServer/Middleware/InnertubeRouter.bs"
import "pkg:/components/Web/PlayletWebServer/Middleware/InvidiousRouter.bs"
import "pkg:/components/Web/PlayletWebServer/Middleware/PlayletInvidiousBackendRouter.bs"
import "pkg:/components/Web/PlayletWebServer/Middleware/PipedBackendRouter.bs"
import "pkg:/components/Web/PlayletWebServer/Middleware/PipedLoginRouter.bs"
import "pkg:/components/Web/PlayletWebServer/Middleware/PlayletLibUrlsRouter.bs"
import "pkg:/components/Web/PlayletWebServer/Middleware/PreferencesRouter.bs"
import "pkg:/components/Web/PlayletWebServer/Middleware/ProfilesRouter.bs"
@@ -65,6 +67,9 @@ function SetupRoutes(server as object)
"/api/innertube/get_drm_license"
' Every write needs the caller's bearer token.
"/playlet-invidious-backend/"
"/playlet-piped-backend/"
' The Piped phone login page posts a plain HTML form.
"/piped/"
]))
if server.settings.WebSocketsEnabled
server.UseRouter(new Http.WebSocketMiddleware())
@@ -86,6 +91,8 @@ function SetupRoutes(server as object)
server.UseRouter(new Http.CacheRouter(server))
server.UseRouter(new Http.RegistryRouter())
server.UseRouter(new Http.PlayletInvidiousBackendRouter(server))
server.UseRouter(new Http.PipedLoginRouter(server))
server.UseRouter(new Http.PipedBackendRouter(server))
server.UseRouter(new Http.InnertubeRouter(server))
etags = new Http.EtagUtils()
+19 -1
View File
@@ -46,7 +46,7 @@
key: "backend.selected",
description: "The backend used for browsing and playing videos.",
type: "radio",
defaultValue: "playlet",
defaultValue: "piped",
options: [
{
displayText: "Playlet (local)",
@@ -56,10 +56,28 @@
displayText: "Invidious",
value: "invidious",
},
{
displayText: "Piped",
value: "piped",
},
],
},
],
},
{
displayText: "Piped",
key: "piped",
description: "Piped backend preferences",
children: [
{
displayText: "Instance",
key: "piped.instance",
description: "Piped API instance to use. Example: https://api.piped.spaghet.io",
type: "string",
defaultValue: "https://api.piped.spaghet.io",
},
],
},
{
displayText: "Content Feed",
key: "content_feed",
Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB