Innertube continuations (#522)

* Search continuations

* add another type of playlists

* Continuation for search and channels working

* Playlist continuation

* Fix pagination - what a fucking mess I've created

* web app fix

* Changelog
This commit is contained in:
Brahim Hadriche authored and GitHub committed 2024-12-25 14:07:48 -05:00
1 parent f6e23ad7d9
commit e23da56b37
15 files changed
+293 -96

No files matched your search

+1
View File
@@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
- Support for auto-generated channels in Playlet backend
- Support for continuation/pagination in Playlet backend: search, channels and playlists load more content as you scroll
### Fixed
@@ -7,7 +7,8 @@
<field id="loadState" type="string" />
<!-- index in a feed -->
<field id="feedSourcesIndex" type="integer" value="-1" />
<!--
<field id="continuation" type="string" />
<!--
For some strange reason, the "author" field can only be set once.
If you try to set it again, it will not be updated, with type mismatch warning:
@@ -18,7 +18,10 @@ function PlaylistContentTask(input as object) as object
while true
index = contentNode.getChildCount()
response = service.GetPlaylist(contentNode.playlistId, index, m.top.cancellation)
continuation = contentNode.continuation
hadContinuation = not StringUtils.IsNullOrEmpty(continuation)
response = service.GetPlaylist(contentNode.playlistId, index, continuation, m.top.cancellation)
if m.top.cancel
contentNode.loadState = FeedLoadState.None
@@ -59,7 +62,8 @@ function PlaylistContentTask(input as object) as object
videoCount = ValidInt(metadata.videoCount)
if metadata.videos.Count() = 0 or childCount >= videoCount
hasContinuation = not StringUtils.IsNullOrEmpty(metadata.continuation)
if (hadContinuation and not hasContinuation) or (metadata.videos.Count() = 0 or childCount >= videoCount)
contentNode.loadState = FeedLoadState.Loaded
return {
success: true
@@ -1,15 +1,19 @@
namespace Innertube
function CreateBrowseRequest(browseId as string, clienType as Innertube.ClientType, params as string) as object
function CreateBrowseRequest(browseId as string, clienType as Innertube.ClientType, params = "" as string, continuation = "" as string) as object
deviceInfo = CreateObject("roDeviceInfo")
payload = {
"browseId": browseId
"context": Innertube.CreateContext(clienType, deviceInfo, "")
}
if not StringUtils.IsNullOrEmpty(params)
payload["params"] = params
if not StringUtils.IsNullOrEmpty(continuation)
payload["continuation"] = continuation
else
payload["browseId"] = browseId
if not StringUtils.IsNullOrEmpty(params)
payload["params"] = params
end if
end if
request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/browse?prettyPrint=false&alt=json", payload)
@@ -84,8 +84,24 @@ namespace InnertubeService
}
end function
function Search(query as string, searchFilters as object, cancellation = invalid as object) as object
return Innertube.Search(query, searchFilters, cancellation)
function Search(query as string, options = invalid as object) as object
searchFilters = invalid
continuation = ""
cancellation = invalid
if options <> invalid
if options.DoesExist("searchFilters")
searchFilters = options.searchFilters
end if
if options.DoesExist("continuation")
continuation = options.continuation
end if
if options.DoesExist("cancellation")
cancellation = options.cancellation
end if
end if
return Innertube.Search(query, searchFilters, continuation, cancellation)
end function
function GetTrending(options = invalid as object) as object
@@ -150,7 +166,7 @@ namespace InnertubeService
end if
end if
request = Innertube.CreateBrowseRequest(browserId, Innertube.ClientType.Tv, "")
request = Innertube.CreateBrowseRequest(browserId, Innertube.ClientType.Tv)
if access_token <> invalid
request.Header("Authorization", "Bearer " + access_token)
end if
@@ -166,19 +182,23 @@ namespace InnertubeService
end function
function GetChannel(channelId as string, options = invalid as object) as object
cancellation = invalid
continuation = ""
params = ""
cancellation = invalid
if options <> invalid
if options.DoesExist("cancellation")
cancellation = options.cancellation
if options.DoesExist("continuation")
continuation = options.continuation
end if
if options.DoesExist("params")
params = options.params
end if
if options.DoesExist("cancellation")
cancellation = options.cancellation
end if
end if
request = Innertube.CreateBrowseRequest(channelId, Innertube.ClientType.Web, params)
request = Innertube.CreateBrowseRequest(channelId, Innertube.ClientType.Web, params, continuation)
request.Cancellation(cancellation)
response = request.Await()
@@ -191,9 +211,13 @@ namespace InnertubeService
end function
function GetPlaylist(playlistId as string, options = invalid as object) as object
continuation = ""
cancellation = invalid
if options <> invalid
if options.DoesExist("continuation")
continuation = options.continuation
end if
if options.DoesExist("cancellation")
cancellation = options.cancellation
end if
@@ -203,7 +227,7 @@ namespace InnertubeService
playlistId = "VL" + playlistId
end if
request = Innertube.CreateBrowseRequest(playlistId, Innertube.ClientType.Web, "")
request = Innertube.CreateBrowseRequest(playlistId, Innertube.ClientType.Web, "", continuation)
request.Cancellation(cancellation)
response = request.Await()
@@ -48,6 +48,7 @@ namespace Innertube
"channelRenderer": ParseChannelRenderer
"gridChannelRenderer": ParseGridChannelRenderer
"playlistRenderer": ParsePlaylistRenderer
"gridPlaylistRenderer": ParseGridPlaylistRenderer
"lockupViewModel": ParseLockupViewModel
"shortsLockupViewModel": ParseShortsLockupViewModel
"tvBrowseRenderer": ParseTvBrowseRenderer
@@ -58,7 +59,8 @@ namespace Innertube
"gridRenderer": ParseGridRenderer
"richGridRenderer": ParseRichGridRenderer
"richItemRenderer": ParseRichItemRenderer
"continuationItemRenderer": ParseNotImplemented
"continuationItemRenderer": ParseContinuationItemRenderer
"appendContinuationItemsAction": ParseAppendContinuationItemsAction
' Posts not yet supported
"postRenderer": ParseNotImplemented
' a "View all posts" button
@@ -67,7 +69,7 @@ namespace Innertube
"horizontalCardListRenderer": ParseNotImplemented
' expandableTabRenderer contains the search tab with a channel. Ignored.
"expandableTabRenderer": ParseNotImplemented
"clickTrackingParams": ParseNotImplemented
}
end function
@@ -468,6 +470,69 @@ namespace Innertube
return invalid
end function
function ParseGridPlaylistRenderer(nodeData as object, context as object) as object
playlistId = nodeData["playlistId"]
if not IsString(playlistId)
LogWarn("Invalid playlist ID", nodeData)
return invalid
end if
author = invalid
authorId = invalid
authorPossibleNodes = ["shortBylineText", "ownerText", "longBylineText"]
for each authorPossibleNode in authorPossibleNodes
node = nodeData[authorPossibleNode]
author = ParseText(node)
authorId = ObjectUtils.Dig(node, ["runs", 0, "navigationEndpoint", "browseEndpoint", "browseId"])
if author <> "" and authorId <> invalid
exit for
end if
end for
if StringUtils.IsNullOrEmpty(author) and StringUtils.IsNullOrEmpty(authorId)
if IsString(context.currentAuthor) and IsString(context.currentAuthorId)
author = context.currentAuthor
authorId = context.currentAuthorId
end if
end if
videoCountText = ""
thumbnailOverlays = nodeData["thumbnailOverlays"]
if IsArray(thumbnailOverlays)
for each overlay in thumbnailOverlays
videoCountText = ParseText(ObjectUtils.Dig(overlay, ["thumbnailOverlayBottomPanelRenderer", "text"]))
if videoCountText <> ""
exit for
end if
end for
end if
if videoCountText = ""
videoCountText = ParseText(nodeData["videoCountText"])
end if
if videoCountText = ""
videoCountText = ParseText(nodeData["videoCountShortText"])
end if
videoCount = ParseText(nodeData["videoCount"])
if videoCount = ""
videoCount = ParseText(nodeData["videoCountShortText"])
end if
videoCount = videoCount.ToInt()
playlist = {
"type": "playlist"
"playlistId": playlistId
"title": ParseText(nodeData["title"])
"playlistThumbnail": ObjectUtils.Dig(nodeData, ["thumbnail", "thumbnails", 0, "url"])
"author": author
"authorId": authorId
"videoCount": videoCount
"videoCountText": videoCountText
}
PushFeedItem(playlist, context)
return invalid
end function
function ParseLockupViewModel(nodeData as object, context as object) as object
contentType = ValidString(nodeData["contentType"])
if contentType = "LOCKUP_CONTENT_TYPE_PLAYLIST"
@@ -717,6 +782,22 @@ namespace Innertube
return nodeData["content"]
end function
function ParseContinuationItemRenderer(nodeData as object, context as object) as object
continuation = ObjectUtils.Dig(nodeData, ["continuationEndpoint", "continuationCommand", "token"])
if IsString(continuation)
' In Playlists there are 2 continuation items, and one of them is useless...
' TODO:P1 figure this out
if StringUtils.IsNullOrEmpty(context.currentFeed.continuation)
context.currentFeed.continuation = continuation
end if
end if
return invalid
end function
function ParseAppendContinuationItemsAction(nodeData as object, context as object) as object
return nodeData["continuationItems"]
end function
function ParseText(data as object) as string
if data = invalid
return ""
@@ -9,8 +9,8 @@ namespace Innertube
return []
end if
data = UnwrapContainer(responseData)
if data = invalid
containers = GetContainers(responseData)
if containers.Count() = 0
return []
end if
@@ -29,7 +29,7 @@ namespace Innertube
generateVideoThumbnails: true
})
Innertube.ParseNode(data, context)
Innertube.ParseNode(containers, context)
if context.currentFeed <> invalid and (context.currentFeed.items.Count() > 0 or context.currentFeed.title <> "")
context.feeds.Push(context.currentFeed)
@@ -127,12 +127,16 @@ namespace Innertube
end if
items = []
continuation = invalid
feeds = ParseResponse(responseData, { "currentAuthor": author, "currentAuthorId": authorId })
if feeds.Count() > 0
items = ValidArray(feeds[0].items)
if feeds[0].DoesExist("continuation")
continuation = feeds[0].continuation
end if
end if
return {
channel = {
"author": author
"authorId": authorId
"authorThumbnails": thumbnails
@@ -142,6 +146,12 @@ namespace Innertube
"tabsParams": tabsParams
"items": items
}
if continuation <> invalid
channel["continuation"] = continuation
end if
return channel
end function
function ParsePlaylistPageResponse(responseData as object) as object
@@ -198,23 +208,21 @@ namespace Innertube
feeds = ParseResponse(responseData)
if feeds.Count() > 0
playlist["videos"] = ValidArray(feeds[0].items)
if feeds[0].DoesExist("continuation")
playlist["continuation"] = feeds[0].continuation
end if
end if
return playlist
end function
function UnwrapContainer(responseData as object) as object
if responseData.DoesExist("contents")
return responseData["contents"]
end if
if responseData.DoesExist("response")
return responseData["response"]
end if
data = ObjectUtils.Dig(responseData, ["onResponseReceivedActions", 0])
if data <> invalid
return data
end if
return responseData
function GetContainers(responseData as object) as object
return [
responseData["contents"]
responseData["response"]
responseData["onResponseReceivedActions"]
responseData["onResponseReceivedCommands"]
]
end function
end namespace
@@ -3,18 +3,22 @@ import "pkg:/components/Services/Innertube/Parser.bs"
namespace Innertube
function Search(query as string, searchFilters as object, cancellation = invalid as object) as object
function Search(query as string, searchFilters as object, continuation = "" as string, cancellation = invalid as object) as object
deviceInfo = CreateObject("roDeviceInfo")
payload = {
query: query
context: Innertube.CreateContext(Innertube.ClientType.WEB, deviceInfo, "")
}
if searchFilters <> invalid and searchFilters.Count() > 0
params = Innertube.GetEncodedSearchFilters(searchFilters)
if params <> ""
payload["params"] = Innertube.GetEncodedSearchFilters(searchFilters)
if continuation <> ""
payload["continuation"] = continuation
else
payload["query"] = query
if searchFilters <> invalid and searchFilters.Count() > 0
params = Innertube.GetEncodedSearchFilters(searchFilters)
if params <> ""
payload["params"] = Innertube.GetEncodedSearchFilters(searchFilters)
end if
end if
end if
@@ -162,7 +162,7 @@ namespace Invidious
return request.Await()
end function
function GetPlaylist(playlistId as string, index = 0 as integer, cancellation = invalid as object) as object
function GetPlaylist(playlistId as string, index = 0 as integer, continuation = "" as string, cancellation = invalid as object) as object
authToken = m.invidiousNode.authToken
' There's no need to use auth, unless the playlist is from Invidious
' (starts with "IV") because it can be a private playlist from logged user.
@@ -176,7 +176,11 @@ namespace Invidious
request = HttpClient.Get(url)
end if
request.QueryParam("index", index)
if continuation <> ""
request.QueryParam("continuation", continuation)
else
request.QueryParam("index", index)
end if
request.Cancellation(cancellation)
return request.Await()
@@ -215,19 +219,24 @@ namespace Invidious
end if
feedSourceState.paginationType = endpoint.paginationType
if feedSourceState.paginationType = PaginationType.Pages
continuation = feedSourceState.continuation
hasContinuation = not StringUtils.IsNullOrEmpty(continuation)
if not hasContinuation
feedSourceState.queryParams.Delete("continuation")
end if
if feedSourceState.paginationType = PaginationType.Continuation or hasContinuation
if hasContinuation
feedSourceState.queryParams.continuation = continuation
end if
feedSourceState.queryParams.Delete("page")
else if feedSourceState.paginationType = PaginationType.Pages
if not IsInt(feedSourceState.page)
feedSourceState.page = 0
end if
feedSourceState.page += 1
feedSourceState.queryParams.page = feedSourceState.page
else if feedSourceState.paginationType = PaginationType.Continuation
continuation = feedSourceState.continuation
if not StringUtils.IsNullOrEmpty(continuation)
feedSourceState.queryParams.continuation = continuation
else
feedSourceState.queryParams.Delete("continuation")
end if
end if
feedSource.state = feedSourceState
@@ -345,9 +354,12 @@ namespace Invidious
if response.StatusCode() = 200
json = response.Json()
return {
items: json
}
if IsArray(json)
json = {
items: json
}
end if
return json
end if
return invalid
end function
@@ -372,9 +384,13 @@ namespace Invidious
if statusCode = 200
json = response.Json()
return {
result = {
items: json.videos
}
if json.continuation <> invalid
result.continuation = json.continuation
end if
return result
end if
return invalid
end function
@@ -100,6 +100,8 @@ namespace InvidiousContent
PlaylistSetThumbnail(node, "thumbnail", item, instance)
PlaylistSetThumbnail(node, "thumbnailBackground", item, instance, "maxres")
node.continuation = ValidString(item.continuation)
return node
end function
@@ -55,6 +55,7 @@ function VideoRowListRowContentTask(input as object) as object
end if
feedSource = service.MarkFeedPagination(feedContentNode)
hadContinuation = not StringUtils.IsNullOrEmpty(feedSource.state.continuation)
response = service.MakeRequest(feedSource, feedSource.state.queryParams, m.top.cancellation)
@@ -109,15 +110,13 @@ function VideoRowListRowContentTask(input as object) as object
feedContentNode.appendChildren(itemNodes)
hasContinuation = not StringUtils.IsNullOrEmpty(response.result.continuation)
if hasContinuation
feedSource.state.continuation = response.result.continuation
end if
feedSource.state.continuation = ValidString(response.result.continuation)
if response.result.items.Count() > 0
pageType = feedSource.state.paginationType
if response.result.isLastPage = true
if response.result.isLastPage = true or (hadContinuation and not hasContinuation)
feedSource.state.loadState = FeedLoadState.Loaded
else if pageType = PaginationType.Continuation and hasContinuation
else if hasContinuation
feedSource.state.loadState = FeedLoadState.LoadedPage
else if pageType = PaginationType.Pages
feedSource.state.loadState = FeedLoadState.LoadedPage
@@ -65,6 +65,7 @@ namespace Http
response = context.response
query = request.query.q
continuation = request.query.continuation
searchFilters = {}
sort = request.query.sort
@@ -88,13 +89,21 @@ namespace Http
searchFilters.features = features.Split(",")
end if
feeds = InnertubeService.Search(query, searchFilters)
options = {}
if searchFilters.Count() > 0
options.searchFilters = searchFilters
end if
if not StringUtils.IsNullOrEmpty(continuation)
options.continuation = continuation
end if
feeds = InnertubeService.Search(query, options)
if not IsArray(feeds) or feeds.Count() = 0
response.Default(500, "Failed to search")
return true
end if
response.Json(ValidArray(feeds[0].items))
response.Json(feeds[0])
return true
end function
@@ -138,18 +147,23 @@ namespace Http
playlistId = route.Mid("/playlet-invidious-backend/api/v1/playlists/".Len())
playlist = InnertubeService.GetPlaylist(playlistId)
options = {}
continuation = request.query.continuation
if not StringUtils.IsNullOrEmpty(continuation)
options.continuation = continuation
end if
playlist = InnertubeService.GetPlaylist(playlistId, options)
if playlist = invalid
response.Default(500, "Failed to get playlist")
return true
end if
' TODO: Implement continuation
index = request.query.index
if not StringUtils.IsNullOrEmpty(index)
index = index.ToInt()
if index > 0
LogWarn("Playlist continuation is not implemented yet")
if index > 1
LogError("Playlet backend does not use playlist pagination (use continuation instead)")
playlist.videos = []
end if
end if
@@ -166,9 +180,16 @@ namespace Http
channelAndTab = route.Mid("/playlet-invidious-backend/api/v1/channels/".Len())
channelAndTab = channelAndTab.Split("/")
options = {}
continuation = request.query.continuation
if not StringUtils.IsNullOrEmpty(continuation)
options.continuation = continuation
end if
if channelAndTab.Count() = 1
channelId = channelAndTab[0]
channel = InnertubeService.GetChannel(channelId)
channel = InnertubeService.GetChannel(channelId, options)
if channel = invalid
response.Default(500, "Failed to get channel")
return true
@@ -180,22 +201,33 @@ namespace Http
channelId = channelAndTab[0]
_tab = channelAndTab[1]
params = ValidString(request.query.params)
params = request.query.params
if not StringUtils.IsNullOrEmpty(params)
options.params = params
end if
channel = InnertubeService.GetChannel(channelId, { "params": params })
channel = InnertubeService.GetChannel(channelId, options)
if channel = invalid
response.Default(500, "Failed to get channel")
return true
end if
if _tab = "playlists" or _tab = "podcasts" or _tab = "releases"
response.Json({
result = {
"playlists": channel.items
})
}
if channel.DoesExist("continuation")
result.continuation = channel.continuation
end if
response.Json(result)
else
response.Json({
result = {
"videos": channel.items
})
}
if channel.DoesExist("continuation")
result.continuation = channel.continuation
end if
response.Json(result)
end if
return true
+28 -12
View File
@@ -28,7 +28,8 @@ export class InvidiousApi {
return await this.cachedFetch(url, 60 * 60 * 24);
}
public async search(query: string, filters: any, page: number = 1) {
// need to change this
public async search(query: string, filters: any, page: number, continuation: string | undefined) {
// TODO:P2 use a FeedSource similar to brightscript version
let url = `${this.instance}/api/v1/search?q=${encodeURIComponent(query)}&region=${this.userCountryCode}`;
for (let filter in filters) {
@@ -44,9 +45,18 @@ export class InvidiousApi {
url += `&${filter}=${filters[filter].join(',')}`;
}
}
url += `&page=${page}`;
if (continuation) {
url += `&continuation=${encodeURIComponent(continuation)}`;
} else {
url += `&page=${page}`;
}
const response = await fetch(url);
return await response.json();
let json = await response.json();
if (Array.isArray(json)) {
json = { items: json };
}
return json;
}
public async getVideoMetadata(videoId: string) {
@@ -89,19 +99,20 @@ export class InvidiousApi {
feedSourceState.paginationType = endpoint.paginationType
if (feedSourceState.paginationType === "Pages") {
if (!Number.isInteger(feedSourceState.page)) {
feedSourceState.page = 0;
}
feedSourceState.page += 1;
feedSourceState.queryParams.page = feedSourceState.page;
} else if (feedSourceState.paginationType === "Continuation") {
const continuation = feedSourceState.continuation;
const continuation = feedSourceState.continuation;
if (feedSourceState.paginationType === "Continuation" || continuation) {
if (continuation) {
feedSourceState.queryParams.continuation = continuation;
} else {
delete feedSourceState.queryParams.continuation;
}
delete feedSourceState.queryParams.page;
} else if (feedSourceState.paginationType === "Pages") {
if (!Number.isInteger(feedSourceState.page)) {
feedSourceState.page = 0;
}
feedSourceState.page += 1;
feedSourceState.queryParams.page = feedSourceState.page;
}
}
@@ -188,12 +199,17 @@ export class InvidiousApi {
}
private async DefaultHandler(feedSource, responseJson) {
return { items: responseJson };
// if is array
if (Array.isArray(responseJson)) {
responseJson = { items: responseJson };
}
return responseJson;
}
private async PlaylistHandler(feedSource, responseJson) {
return {
items: responseJson.videos,
continuation: responseJson.continuation
};
}
@@ -21,6 +21,7 @@
let searchBoxText = "";
let suggestions: { suggestions: any[] } = { suggestions: [] };
let page = 1;
let searchContinuation = "";
let videos = [];
let searchHistory = [];
let isLoading = false;
@@ -85,11 +86,12 @@
async function suggestionClicked(query) {
searchBoxText = query;
page = 1;
searchContinuation = "";
videos = [];
await searchVideos();
await searchVideos("");
}
async function searchVideos() {
async function searchVideos(continuation: string | undefined) {
suggestions = { suggestions: [] };
if (searchBoxText.length === 0) {
return;
@@ -97,12 +99,14 @@
try {
isLoading = true;
const newVideos = await invidiousApi.search(
const response = await invidiousApi.search(
searchBoxText,
searchFilters,
page
page,
continuation
);
videos = [...videos, ...newVideos];
videos = [...videos, ...response.items];
searchContinuation = response.continuation || "";
} finally {
isLoading = false;
}
@@ -122,7 +126,7 @@
e.preventDefault();
page = 1;
videos = [];
await searchVideos();
await searchVideos("");
}}
>
<div class="join w-full border border-neutral rounded-full">
@@ -148,7 +152,7 @@
on:click={async () => {
page = 1;
videos = [];
await searchVideos();
await searchVideos("");
}}
>
<div class="h-6">
@@ -206,7 +210,7 @@
class="btn w-1/2"
on:click={async () => {
page++;
await searchVideos();
await searchVideos(searchContinuation);
}}
>
{$tr("Load more")}
@@ -151,6 +151,7 @@
}
invidiousApi.markFeedSourcePagination(feedSource);
let hadContinuation = !!feedSource.state.continuation;
try {
const result = await invidiousApi.makeRequest(feedSource);
@@ -163,14 +164,14 @@
continue;
}
const hasContinuation = !!result.continuation;
if (hasContinuation) {
feedSource.state.continuation = result.continuation;
}
let hasContinuation = !!result.continuation;
feedSource.state.continuation = result.continuation || "";
if (result.items.length > 0) {
const paginationType = feedSource.state.paginationType;
if (paginationType === "Continuation" && hasContinuation) {
if (hadContinuation && !hasContinuation) {
feedSource.state.loadState = FeedLoadState.Loaded;
} else if (paginationType === "Continuation" && hasContinuation) {
feedSource.state.loadState = FeedLoadState.LoadedPage;
} else if (paginationType === "Pages") {
feedSource.state.loadState = FeedLoadState.LoadedPage;