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
+292 -95

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