From d8417ee90c1e169164162a1080636c44638b5f99 Mon Sep 17 00:00:00 2001 From: Brahim Hadriche Date: Fri, 20 Jun 2025 11:53:41 -0400 Subject: [PATCH] Improve performance of video bookmarks (#662) * Improve performance of video bookmarks * remove test code --- CHANGELOG.md | 4 +- .../BookmarksService/BookmarksService.bs | 4 + .../Services/Innertube/InnertubeService.bs | 61 ++++--- .../Services/Innertube/NodesParser.bs | 168 ++++++++++++++++++ .../VideoQueue/VideoQueueViewContentTask.bs | 14 +- .../PlayletInvidiousBackendRouter.bs | 23 ++- .../src/config/invidious_video_api.yaml | 4 + playlet-web/src/lib/Api/PlayletApi.ts | 2 +- 8 files changed, 252 insertions(+), 28 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6ea70548..0b91b0df 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] -- Nothing worth mentioning yet. +### Fixed + +- Improve performance of video bookmarks, by avoiding `/player` endpoint and caching results ## [0.40.5] - 2025-06-19 diff --git a/playlet-lib/src/components/Services/BookmarksService/BookmarksService.bs b/playlet-lib/src/components/Services/BookmarksService/BookmarksService.bs index d34df216..38930d9c 100644 --- a/playlet-lib/src/components/Services/BookmarksService/BookmarksService.bs +++ b/playlet-lib/src/components/Services/BookmarksService/BookmarksService.bs @@ -109,6 +109,10 @@ end function function AddVideoBookmark(id as string, groupName as string) bookmarkGroupNode = GetOrCreateBookmarkGroup(groupName) + ' TODO:P1 instead of just storying the video id, we should store + ' enough metadata for display (videoId, author, authorId, title, + ' duration, isLive) that way all data is offline and avoid making + ' a request altogether. feedSource = { "apiType": "Invidious" "endpoint": "video_info" diff --git a/playlet-lib/src/components/Services/Innertube/InnertubeService.bs b/playlet-lib/src/components/Services/Innertube/InnertubeService.bs index b5d36fb5..2b8737fe 100644 --- a/playlet-lib/src/components/Services/Innertube/InnertubeService.bs +++ b/playlet-lib/src/components/Services/Innertube/InnertubeService.bs @@ -113,33 +113,50 @@ namespace InnertubeService } end if - responseData = ObjectUtils.Dig(responseData, ["contents", "twoColumnWatchNextResults", "playlist", "playlist"]) - if responseData = invalid - ' Sometimes the response doesn't contain a playlist. - ' The theory here is that when a private video is in the list, the created playlist - ' is no longer publicly available. That's why it is not returned. Also happens with - ' a deleted video. - ' A retry after a short sleep SOMETIMES fixes this (but not always). - ' TODO:P1: Figure out why this happens and if there's a better way to handle it. - if retry - LogWarn("Response data missing playlist. Retrying in a bit...") - newOptions = {} - if options <> invalid - newOptions.Append(options) + ' If we're fetching more than one video, we want to search for the playlist + if videoIds.Count() > 1 + responseData = ObjectUtils.Dig(responseData, ["contents", "twoColumnWatchNextResults", "playlist", "playlist"]) + if responseData = invalid + ' Sometimes the response doesn't contain a playlist. + ' The theory here is that when a private video is in the list, the created playlist + ' is no longer publicly available. That's why it is not returned. Also happens with + ' a deleted video. + ' A retry after a short sleep SOMETIMES fixes this (but not always). + ' TODO:P1: Figure out why this happens and if there's a better way to handle it. + if retry + LogWarn("Response data missing playlist. Retrying in a bit...") + newOptions = {} + if options <> invalid + newOptions.Append(options) + end if + newOptions["retry"] = false + sleep(200 + Rnd(500)) + return GetVideoInfoBatched(videoIds, newOptions) + else + LogWarn("Response data missing playlist. Not retrying.") end if - newOptions["retry"] = false - sleep(200 + Rnd(500)) - return GetVideoInfoBatched(videoIds, newOptions) - else - LogWarn("Response data missing playlist. Not retrying.") end if end if feeds = Innertube.ParseResponseDataForFeeds(responseData) - if feeds.Count() > 0 - return { - videos: ValidArray(feeds[0].items) - } + + if videoIds.Count() > 1 + if feeds.Count() > 0 + return { + videos: ValidArray(feeds[0].items) + } + end if + else + if feeds.Count() > 0 + foundVideos = feeds[0].items + for each video in foundVideos + if video.videoId = videoIds[0] + return { + videos: [video] + } + end if + end for + end if end if return { diff --git a/playlet-lib/src/components/Services/Innertube/NodesParser.bs b/playlet-lib/src/components/Services/Innertube/NodesParser.bs index 08bfdb05..fe128677 100644 --- a/playlet-lib/src/components/Services/Innertube/NodesParser.bs +++ b/playlet-lib/src/components/Services/Innertube/NodesParser.bs @@ -44,6 +44,7 @@ namespace Innertube "twoColumnSearchResultsRenderer": ParseTwoColumnSearchResultsRenderer "singleColumnBrowseResultsRenderer": ParseSingleColumnBrowseResultsRenderer "twoColumnBrowseResultsRenderer": ParseTwoColumnBrowseResultsRenderer + "twoColumnWatchNextResults": ParseTwoColumnWatchNextResults "watchNextEndScreenRenderer": ParseWatchNextEndScreenRenderer "tabRenderer": ParseTabRenderer "sectionListRenderer": ParseSectionListRenderer @@ -61,6 +62,8 @@ namespace Innertube "playlistVideoListContinuation": ParsePlaylistVideoListContinuation "videoRenderer": ParseVideoRenderer "gridVideoRenderer": ParseGridVideoRenderer + "compactVideoRenderer": ParseCompactVideoRenderer + "videoPrimaryInfoRenderer": ParseVideoPrimaryInfoRenderer "channelVideoPlayerRenderer": ParseChannelVideoPlayerRenderer "playlistVideoRenderer": ParsePlaylistVideoRenderer "playlistPanelVideoRenderer": ParsePlaylistPanelVideoRenderer @@ -88,6 +91,14 @@ namespace Innertube "gridContinuation": ParseGridContinuation "tvSurfaceContentContinuation": ParseTvSurfaceContentContinuation ' Ignored nodes: + ' Contains comments "teaser". + "commentsEntryPointHeaderRenderer": ParseNotImplemented + ' Contains the owner of the video from "videoPrimaryInfoRenderer" + "videoSecondaryInfoRenderer": ParseNotImplemented + ' Empty node? Perhaps used in some cases + "compositeVideoPrimaryInfoRenderer": ParseNotImplemented + ' An information panel, could contain a link to some website, or a message. + "infoPanelContainerRenderer": ParseNotImplemented ' When you mispell something in the search bar, this renderer shows "didYouMeanRenderer": ParseNotImplemented ' A list of subscribers in a channel with a CTA to subscribe. @@ -136,6 +147,32 @@ namespace Innertube return nodeData["tabs"] end function + function ParseTwoColumnWatchNextResults(nodeData as object, _context as object) as object + subItems = [] + + results = ObjectUtils.Dig(nodeData, ["results", "results", "contents"]) + if results <> invalid + subItems.Push(results) + end if + + secondaryResults = ObjectUtils.Dig(nodeData, ["secondaryResults", "secondaryResults", "results"]) + if secondaryResults <> invalid + subItems.Push(secondaryResults) + end if + ' Technically, this playlist would have its own title, and should count as a separate feed. + ' For now, we just add it to the current feed. + playlist = ObjectUtils.Dig(nodeData, ["playlist", "playlist", "contents"]) + if playlist <> invalid + subItems.Push(playlist) + end if + + if subItems.Count() = 0 + LogWarn("No results found in TwoColumnWatchNextResults", nodeData) + return invalid + end if + return subItems + end function + function ParseWatchNextEndScreenRenderer(nodeData as object, _context as object) as object return nodeData["results"] end function @@ -451,6 +488,137 @@ namespace Innertube return invalid end function + function ParseCompactVideoRenderer(nodeData as object, context as object) as object + videoId = nodeData["videoId"] + if not IsString(videoId) + LogWarn("Invalid video ID", nodeData) + return invalid + end if + + author = invalid + authorId = invalid + authorPossibleNodes = ["ownerText", "shortBylineText", "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 + + viewCountText = ParseText(nodeData["shortViewCountText"]) + if viewCountText = "" + viewCountText = ParseText(nodeData["viewCountText"]) + end if + + publishedText = ParseText(nodeData["publishedTimeText"]) + lengthText = ParseText(nodeData["lengthText"]) + if lengthText = "" + thumbnailOverlays = nodeData["thumbnailOverlays"] + if IsArray(thumbnailOverlays) + for each overlay in thumbnailOverlays + parsedTimeStatusRenderer = ParseThumbnailOverlayTimeStatusRenderer(overlay) + if parsedTimeStatusRenderer <> invalid + lengthText = parsedTimeStatusRenderer.text + if lengthText <> "" + exit for + end if + end if + end for + end if + end if + + if context.generateVideoThumbnails = true + videoThumbnails = GenerateVideoThumbnails(videoId) + else + videoThumbnails = ObjectUtils.Dig(nodeData, ["thumbnail", "thumbnails"]) + if videoThumbnails = invalid + videoThumbnails = GenerateVideoThumbnails(videoId) + end if + end if + + isUpcoming = false + liveNow = ValidString(ObjectUtils.Dig(nodeData, ["badges", 0, "metadataBadgeRenderer", "icon", "iconType"])) = "LIVE" + thumbnailOverlays = nodeData["thumbnailOverlays"] + if IsArray(thumbnailOverlays) + for each overlay in thumbnailOverlays + parsedTimeStatusRenderer = ParseThumbnailOverlayTimeStatusRenderer(overlay) + if parsedTimeStatusRenderer <> invalid + if parsedTimeStatusRenderer.isShort + if context.disableShorts = true + LogInfo("Skipping Short based on user settings") + return invalid + end if + end if + + liveNow = liveNow or parsedTimeStatusRenderer.isLive + isUpcoming = isUpcoming or parsedTimeStatusRenderer.isUpcoming + end if + end for + end if + + premiereTimestamp = ObjectUtils.Dig(nodeData, ["upcomingEventData", "startTime"]) + if IsString(premiereTimestamp) + premiereTimestamp = premiereTimestamp.ToInt() + isUpcoming = true + end if + + video = { + "type": "video" + "videoId": videoId + "author": author + "authorId": authorId + "title": ParseText(nodeData["title"]) + "videoThumbnails": videoThumbnails + "viewCountText": viewCountText + "publishedText": publishedText + "lengthText": lengthText + "liveNow": liveNow + } + + if isUpcoming + video["isUpcoming"] = true + video["premiereTimestamp"] = premiereTimestamp + end if + PushFeedItem(video, context) + return invalid + end function + + function ParseVideoPrimaryInfoRenderer(nodeData as object, context as object) as object + videoId = nodeData["videoId"] + if not IsString(videoId) + videoId = ObjectUtils.Dig(nodeData, ["updatedMetadataEndpoint", "updatedMetadataEndpoint", "videoId"]) + if not IsString(videoId) + LogWarn("Invalid video ID", nodeData) + return invalid + end if + end if + + title = ParseText(nodeData["title"]) + videoThumbnails = GenerateVideoThumbnails(videoId) + + publishedText = ParseText(nodeData["relativeDateText"]) + if publishedText = "" + publishedText = ParseText(nodeData["dateText"]) + end if + + viewCountText = ParseText(ObjectUtils.Dig(nodeData, ["viewCount", "videoViewCountRenderer", "viewCount"])) + + ' TODO:P2 the owner of the video is under videoSecondaryInfoRenderer in a neibouring node. + video = { + "type": "video" + "videoId": videoId + "title": title + "videoThumbnails": videoThumbnails + "viewCountText": viewCountText + "publishedText": publishedText + } + + PushFeedItem(video, context) + return invalid + end function + function ParseChannelVideoPlayerRenderer(nodeData as object, context as object) as object videoId = nodeData["videoId"] if not IsString(videoId) diff --git a/playlet-lib/src/components/VideoQueue/VideoQueueViewContentTask.bs b/playlet-lib/src/components/VideoQueue/VideoQueueViewContentTask.bs index 439113fd..86d2dec4 100644 --- a/playlet-lib/src/components/VideoQueue/VideoQueueViewContentTask.bs +++ b/playlet-lib/src/components/VideoQueue/VideoQueueViewContentTask.bs @@ -26,10 +26,11 @@ function VideoQueueViewContentTask(input as object) as object visitorData: innertubeNode.visitorData } - ' TODO:P1: Use InnertubeService.GetVideoInfoBatched instead of loading each video individually + ' TODO:P1: Use InnertubeService.GetVideoInfoBatched with an array instead of loading each video individually ' TODO:P1: It turns out this might be too much. With a large number of videos ' YouTube starts to rate limit us. ' Need to change it to load on demand using render tracking + ' Or maybe not load this stuff at all. for i = index to videoNodes.Count() - 1 videoNode = videoNodes[i] if not LoadVideoDetail(videoNode, service, instance, requestOptions, backend) @@ -57,12 +58,19 @@ function VideoQueueViewContentTask(input as object) as object return invalid end function -' Returns true if the video was loaded from cache. function LoadVideoDetail(videoNode as object, service as object, instance as string, requestOptions as object, backend as string) as boolean videoId = videoNode.videoId if backend = "playlet" - metadata = InnertubeService.GetVideoMetadata(videoId, requestOptions) + requestOptions["retry"] = false + metadata = InnertubeService.GetVideoInfoBatched([videoId], requestOptions) + if IsArray(metadata.videos) and metadata.videos.Count() > 0 + metadata = metadata.videos[0] + else + metadata = { + "error": "Failed to get video info with video_info_batched=true" + } + end if else metadata = service.GetVideoMetadata(videoId, requestOptions) end if diff --git a/playlet-lib/src/components/Web/PlayletWebServer/Middleware/PlayletInvidiousBackendRouter.bs b/playlet-lib/src/components/Web/PlayletWebServer/Middleware/PlayletInvidiousBackendRouter.bs index d46d9203..55cf84fc 100644 --- a/playlet-lib/src/components/Web/PlayletWebServer/Middleware/PlayletInvidiousBackendRouter.bs +++ b/playlet-lib/src/components/Web/PlayletWebServer/Middleware/PlayletInvidiousBackendRouter.bs @@ -572,17 +572,38 @@ namespace Http videoId = videoId.Left(videoId.InStr("?")) end if raw = request.query.raw <> invalid + videoInfoBatched = request.query.video_info_batched <> invalid options = { "raw": raw "visitorData": m.innertube.visitorData } - metadata = InnertubeService.GetVideoMetadata(videoId, options) + if videoInfoBatched + options["retry"] = false + metadata = InnertubeService.GetVideoInfoBatched([videoId], options) + if IsArray(metadata.videos) and metadata.videos.Count() > 0 + metadata = metadata.videos[0] + else + metadata = { + "error": "Failed to get video info with video_info_batched=true" + } + end if + else + metadata = InnertubeService.GetVideoMetadata(videoId, options) + end if + response.Json(metadata) if metadata.error <> invalid response.http_code = 500 + return true + end if + + ' If we're only interested in video info and not streaming data, + ' we can return longer cache time. + if videoInfoBatched + response.headers["cache-control"] = "public, max-age=259200" ' 3 days end if return true diff --git a/playlet-lib/src/config/invidious_video_api.yaml b/playlet-lib/src/config/invidious_video_api.yaml index 8aba4894..faddb501 100644 --- a/playlet-lib/src/config/invidious_video_api.yaml +++ b/playlet-lib/src/config/invidious_video_api.yaml @@ -96,6 +96,10 @@ video_info: url: /api/v1/videos/{id} responseHandler: VideoInfoHandler cacheSeconds: 259200 # 3 days + queryParams: + video_info_batched: + type: boolean + default: true playlist_info: title: Playlist diff --git a/playlet-web/src/lib/Api/PlayletApi.ts b/playlet-web/src/lib/Api/PlayletApi.ts index d74478f1..cb3723f9 100644 --- a/playlet-web/src/lib/Api/PlayletApi.ts +++ b/playlet-web/src/lib/Api/PlayletApi.ts @@ -4,7 +4,7 @@ export class PlayletApi { static host = () => `http://${getHost()}` static async getVideoInfo(videoId) { - const response = await fetch(`${PlayletApi.host()}/playlet-invidious-backend/api/v1/videos/${videoId}`); + const response = await fetch(`${PlayletApi.host()}/playlet-invidious-backend/api/v1/videos/${videoId}?video_info_batched=true`); return await response.json(); }