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'.
This commit is contained in:
1 parent
4bd5c11f42
commit
ee36c76e8f
7 files changed
+965
-1
No files matched your search
@@ -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/main/piped/playlet-lib.zip
|
||||
|
||||
git_commit_sha=unknown
|
||||
|
||||
|
||||
@@ -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,604 @@
|
||||
import "pkg:/source/utils/StringUtils.bs"
|
||||
import "pkg:/source/utils/Types.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
|
||||
t = type(millis)
|
||||
if t <> "int" and t <> "longint" and t <> "float" and t <> "double"
|
||||
return 0
|
||||
end if
|
||||
value = ValidInt(millis)
|
||||
if value > 100000000000
|
||||
return value / 1000
|
||||
end if
|
||||
return value
|
||||
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
|
||||
|
||||
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
|
||||
|
||||
@@ -0,0 +1,331 @@
|
||||
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"
|
||||
|
||||
' 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
|
||||
|
||||
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 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.UnsupportedAuth(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.UnsupportedAuth(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.UnsupportedAuth(context)
|
||||
end if
|
||||
return false
|
||||
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, {
|
||||
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
|
||||
@@ -8,6 +8,7 @@ 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/PlayletLibUrlsRouter.bs"
|
||||
import "pkg:/components/Web/PlayletWebServer/Middleware/PreferencesRouter.bs"
|
||||
import "pkg:/components/Web/PlayletWebServer/Middleware/ProfilesRouter.bs"
|
||||
@@ -86,6 +87,7 @@ 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.PipedBackendRouter(server))
|
||||
server.UseRouter(new Http.InnertubeRouter(server))
|
||||
|
||||
etags = new Http.EtagUtils()
|
||||
|
||||
@@ -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",
|
||||
|
||||
Reference in new issue
Block a user