From 5b6b5f5ec3ea6ee2ddc30ac82da65e2dd1500fe5 Mon Sep 17 00:00:00 2001 From: Brahim Hadriche Date: Sat, 28 Dec 2024 11:54:12 -0500 Subject: [PATCH] Caching and refactor (#527) * Caching and refactor * Fix and tweak some parsing * Missing imports * refactor --- CHANGELOG.md | 1 + .../SearchScreen/SearchSuggestionsTask.bs | 22 +++- .../Services/Innertube/InnertubeService.bs | 114 ++++++++++++------ .../Services/Innertube/NextEndpoint.bs | 43 ++----- .../Services/Innertube/NodesParser.bs | 38 ++++++ .../components/Services/Innertube/Parser.bs | 76 +++++++++--- .../Services/Innertube/PlayerEndpoint.bs | 46 ++----- .../{ResolveUrl.bs => ResolveUrlEndpoint.bs} | 0 .../{Search.bs => SearchEndpoint.bs} | 38 +++++- .../Services/Invidious/InvidiousService.bs | 28 ++++- .../VideoPlayer/VideoContentTask.bs | 31 ++--- .../VideoPlayerDev/VideoContentTaskDev.bs | 10 +- .../VideoQueue/VideoQueueViewContentTask.bs | 18 +-- .../PlayletWebServer/Middleware/DashRouter.bs | 7 +- .../PlayletInvidiousBackendRouter.bs | 90 +++++++++----- playlet-web/src/lib/Api/InvidiousApi.ts | 3 +- 16 files changed, 357 insertions(+), 208 deletions(-) rename playlet-lib/src/components/Services/Innertube/{ResolveUrl.bs => ResolveUrlEndpoint.bs} (100%) rename playlet-lib/src/components/Services/Innertube/{Search.bs => SearchEndpoint.bs} (73%) diff --git a/CHANGELOG.md b/CHANGELOG.md index 88d0c38b..afc8c010 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed - Crash in player when video ID is invalid +- [Perf] better caching in Playlet backend ## [0.35.2] - 2024-12-27 diff --git a/playlet-lib/src/components/Screens/SearchScreen/SearchSuggestionsTask.bs b/playlet-lib/src/components/Screens/SearchScreen/SearchSuggestionsTask.bs index 12776fea..9497a399 100644 --- a/playlet-lib/src/components/Screens/SearchScreen/SearchSuggestionsTask.bs +++ b/playlet-lib/src/components/Screens/SearchScreen/SearchSuggestionsTask.bs @@ -12,12 +12,18 @@ function SearchSuggestionsTask(input as object) as object return invalid end if - backend = preferencesNode["playback.backend"] - if backend = "playlet" - searchSuggestsions = StringUtils.IsNullOrEmpty(q) ? invalid : InnertubeService.SearchSuggestions(q, m.top.cancellation) + if StringUtils.IsNullOrEmpty(q) + searchSuggestsions = { + suggestions: [] + } else - service = new Invidious.InvidiousService(invidiousNode) - searchSuggestsions = StringUtils.IsNullOrEmpty(q) ? invalid : service.SearchSuggestions(q, m.top.cancellation) + backend = preferencesNode["playback.backend"] + if backend = "playlet" + searchSuggestsions = InnertubeService.SearchSuggestions(q, m.top.cancellation) + else + service = new Invidious.InvidiousService(invidiousNode) + searchSuggestsions = service.SearchSuggestions(q, m.top.cancellation) + end if end if if m.top.cancel @@ -27,7 +33,11 @@ function SearchSuggestionsTask(input as object) as object history = SearchHistoryUtils.GetSaved(preferencesNode, q) if searchSuggestsions <> invalid - history = MergeSearchSuggestions(history, searchSuggestsions.suggestions) + if searchSuggestsions.error <> invalid + LogError(searchSuggestsions.error) + else + history = MergeSearchSuggestions(history, searchSuggestsions.suggestions) + end if end if return { diff --git a/playlet-lib/src/components/Services/Innertube/InnertubeService.bs b/playlet-lib/src/components/Services/Innertube/InnertubeService.bs index 9a173170..2b19d237 100644 --- a/playlet-lib/src/components/Services/Innertube/InnertubeService.bs +++ b/playlet-lib/src/components/Services/Innertube/InnertubeService.bs @@ -4,8 +4,8 @@ import "pkg:/components/Services/Innertube/Context.bs" import "pkg:/components/Services/Innertube/NextEndpoint.bs" import "pkg:/components/Services/Innertube/OAuth.bs" import "pkg:/components/Services/Innertube/PlayerEndpoint.bs" -import "pkg:/components/Services/Innertube/ResolveUrl.bs" -import "pkg:/components/Services/Innertube/Search.bs" +import "pkg:/components/Services/Innertube/ResolveUrlEndpoint.bs" +import "pkg:/components/Services/Innertube/SearchEndpoint.bs" import "pkg:/components/Services/Innertube/SearchFilters.bs" import "pkg:/source/services/HttpClient.bs" import "pkg:/source/utils/CancellationUtils.bs" @@ -45,11 +45,15 @@ namespace InnertubeService playerResponse = playerRequest.Await() if not playerResponse.IsSuccess() - return playerResponse + return { + error: playerResponse.ErrorMessage() + } end if if CancellationUtils.IsCancelled(cancellation) - return invalid + return { + error: "Cancelled" + } end if if fetchNext @@ -57,26 +61,22 @@ namespace InnertubeService end if parsedResponse = Innertube.ParseInnertubePlayerResponse(playerResponse.Json()) + if parsedResponse.error <> invalid + return parsedResponse + end if if fetchNext parsedResponse = Innertube.ParseInnertubeNextResponse(nextResponse.Json(), parsedResponse) end if - if parsedResponse <> invalid - if parsedResponse.Success - playerResponse.OverrideJson(parsedResponse.Metadata) - else - playerResponse.OverrideStatusCode(500) - playerResponse.OverrideErrorMessage(parsedResponse.Error) - end if - end if - - return playerResponse + return parsedResponse end function function GetVideoInfoBatched(videoIds as object, options = invalid as object) as object if not IsArray(videoIds) or videoIds.Count() = 0 - return [] + return { + videos: [] + } end if cancellation = invalid @@ -97,15 +97,27 @@ namespace InnertubeService response = request.Await() if not response.IsSuccess() - return [] + return { + error: response.ErrorMessage() + } end if - responseData = ObjectUtils.Dig(response.Json(), ["contents", "twoColumnWatchNextResults", "playlist", "playlist"]) + responseData = response.Json() + + error = Innertube.ParseResponseDataForError(responseData) + if error <> "" + return { + error: error + } + 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 Innertube creates a playlist for the videoIds, and sometimes ' it chooses to respond without the playlist (perhaps to avoid slow responses). - ' A retry after a short sleep usually fixes this. + ' A retry after a short sleep usually 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 = {} @@ -120,25 +132,22 @@ namespace InnertubeService end if end if - feeds = Innertube.ParseResponse(responseData) + feeds = Innertube.ParseResponseDataForFeeds(responseData) if feeds.Count() > 0 - return ValidArray(feeds[0].items) - end if - - return [] - end function - - function SearchSuggestions(q as string, cancellation = invalid as object) as object - suggestions = Innertube.SearchSuggestions(q, cancellation) - if suggestions = invalid - suggestions = [] + return { + videos: ValidArray(feeds[0].items) + } end if return { - suggestions: suggestions + videos: [] } end function + function SearchSuggestions(q as string, cancellation = invalid as object) as object + return Innertube.SearchSuggestions(q, cancellation) + end function + function Search(query as string, options = invalid as object) as object searchFilters = invalid continuation = "" @@ -189,7 +198,18 @@ namespace InnertubeService end if json = response.Json() - return Innertube.ParseResponse(json) + feeds = Innertube.ParseResponseDataForFeeds(json) + + result = { + feeds: feeds + } + + cacheControl = Innertube.ParseResponseForCacheControl(response) + if cacheControl <> invalid + result["cache-control"] = cacheControl + end if + + return result end function function GetHome(options = invalid as object) as object @@ -233,7 +253,7 @@ namespace InnertubeService end if json = response.Json() - return Innertube.ParseResponse(json) + return Innertube.ParseResponseDataForFeeds(json) end function function GetChannel(channelId as string, options = invalid as object) as object @@ -258,11 +278,20 @@ namespace InnertubeService response = request.Await() if not response.IsSuccess() - return invalid + return { + error: response.ErrorMessage() + } end if json = response.Json() - return Innertube.ParseChannelPageResponse(json) + result = Innertube.ParseChannelPageResponseData(json) + + cacheControl = Innertube.ParseResponseForCacheControl(response) + if cacheControl <> invalid + result["cache-control"] = cacheControl + end if + + return result end function function GetPlaylist(playlistId as string, options = invalid as object) as object @@ -287,11 +316,20 @@ namespace InnertubeService response = request.Await() if not response.IsSuccess() - return invalid + return { + error: response.ErrorMessage() + } end if json = response.Json() - return Innertube.ParsePlaylistPageResponse(json) + result = Innertube.ParsePlaylistPageResponseData(json) + + cacheControl = Innertube.ParseResponseForCacheControl(response) + if cacheControl <> invalid + result["cache-control"] = cacheControl + end if + + return result end function function ResolveUrl(url as string, options = invalid as object) as object @@ -308,7 +346,9 @@ namespace InnertubeService response = request.Await() if not response.IsSuccess() - return invalid + return { + error: response.ErrorMessage() + } end if json = response.Json() diff --git a/playlet-lib/src/components/Services/Innertube/NextEndpoint.bs b/playlet-lib/src/components/Services/Innertube/NextEndpoint.bs index defda88b..a63e0e57 100644 --- a/playlet-lib/src/components/Services/Innertube/NextEndpoint.bs +++ b/playlet-lib/src/components/Services/Innertube/NextEndpoint.bs @@ -1,4 +1,5 @@ import "pkg:/components/Services/Innertube/Context.bs" +import "pkg:/components/Services/Innertube/Parser.bs" import "pkg:/components/Services/Innertube/protos/params.proto.gen.bs" import "pkg:/source/services/HttpClient.bs" import "pkg:/source/utils/Logging.bs" @@ -23,13 +24,12 @@ namespace Innertube end if request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/next?prettyPrint=false&alt=json", payload) - request.Headers({ + headers = { "accept": "*/*" "accept-language": "*" - "user-agent": INNERTUBE_WEB_USER_AGENT - "x-youtube-client-name": INNERTUBE_WEB_CLIENT_NAME - "x-youtube-client-version": INNERTUBE_WEB_CLIENT_VERSION - }) + } + headers.Append(Innertube.CreateHeaders(Innertube.ClientType.Web)) + request.Headers(headers) return request end function @@ -45,13 +45,13 @@ namespace Innertube end function function ParseInnertubeNextResponse(payload as object, parsedResponse as object) as object - if not parsedResponse.Success + if parsedResponse.error <> invalid LogWarn("Invalid parsed response", parsedResponse) return parsedResponse end if - if not IsArray(parsedResponse.Metadata.recommendedVideos) - LogWarn("Invalid recommended videos", parsedResponse.Metadata.recommendedVideos) + if not IsArray(parsedResponse.recommendedVideos) + LogWarn("Invalid recommended videos", parsedResponse.recommendedVideos) return parsedResponse end if @@ -60,30 +60,13 @@ namespace Innertube return parsedResponse end if - endScreenVideos = ObjectUtils.Dig(payload, ["playerOverlays", "playerOverlayRenderer", "endScreen", "watchNextEndScreenRenderer", "results"]) - if not IsArray(endScreenVideos) - LogWarn("Invalid end screen videos", endScreenVideos) - return parsedResponse + endscreen = ObjectUtils.Dig(payload, ["playerOverlays", "playerOverlayRenderer", "endScreen"]) + + feeds = Innertube.ParseResponseDataForFeeds(endscreen, { noContainers: true }) + if feeds.Count() > 0 + parsedResponse.recommendedVideos.Append(ValidArray(feeds[0].items)) end if - for each video in endScreenVideos - videoId = ObjectUtils.Dig(video, ["endScreenVideoRenderer", "videoId"]) - if videoId = invalid - LogWarn("Invalid video ID in end screen video", video) - continue for - end if - - title = ValidString(ObjectUtils.Dig(video, ["endScreenVideoRenderer", "title", "simpleText"])) - author = ValidString(ObjectUtils.Dig(video, ["endScreenVideoRenderer", "shortBylineText", "runs", 0, "text"])) - - parsedResponse.Metadata.recommendedVideos.Push({ - "type": "video" - "videoId": videoId - "title": title - "author": author - }) - end for - return parsedResponse end function diff --git a/playlet-lib/src/components/Services/Innertube/NodesParser.bs b/playlet-lib/src/components/Services/Innertube/NodesParser.bs index fe3260fb..cd76a482 100644 --- a/playlet-lib/src/components/Services/Innertube/NodesParser.bs +++ b/playlet-lib/src/components/Services/Innertube/NodesParser.bs @@ -31,6 +31,7 @@ namespace Innertube return { "twoColumnSearchResultsRenderer": ParseTwoColumnSearchResultsRenderer "twoColumnBrowseResultsRenderer": ParseTwoColumnBrowseResultsRenderer + "watchNextEndScreenRenderer": ParseWatchNextEndScreenRenderer "tabRenderer": ParseTabRenderer "sectionListRenderer": ParseSectionListRenderer "itemSectionRenderer": ParseItemSectionRenderer @@ -46,6 +47,7 @@ namespace Innertube "channelVideoPlayerRenderer": ParseChannelVideoPlayerRenderer "playlistVideoRenderer": ParsePlaylistVideoRenderer "playlistPanelVideoRenderer": ParsePlaylistPanelVideoRenderer + "endScreenVideoRenderer": ParseEndScreenVideoRenderer "channelRenderer": ParseChannelRenderer "gridChannelRenderer": ParseGridChannelRenderer "playlistRenderer": ParsePlaylistRenderer @@ -85,6 +87,10 @@ namespace Innertube return nodeData["tabs"] end function + function ParseWatchNextEndScreenRenderer(nodeData as object, _context as object) as object + return nodeData["results"] + end function + function ParseTabRenderer(nodeData as object, context as object) as object selected = nodeData["selected"] if not ValidBool(selected) @@ -440,6 +446,38 @@ namespace Innertube return invalid end function + function ParseEndScreenVideoRenderer(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 = ["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 + + video = { + "type": "video" + "videoId": videoId + "author": author + "authorId": authorId + "title": ParseText(nodeData["title"]) + "videoThumbnails": ObjectUtils.Dig(nodeData, ["thumbnail", "thumbnails"]) + } + + PushFeedItem(video, context) + return invalid + end function + function ParseChannelRenderer(nodeData as object, context as object) as object channelId = nodeData["channelId"] if not IsString(channelId) diff --git a/playlet-lib/src/components/Services/Innertube/Parser.bs b/playlet-lib/src/components/Services/Innertube/Parser.bs index 57e45514..b5d2d1f0 100644 --- a/playlet-lib/src/components/Services/Innertube/Parser.bs +++ b/playlet-lib/src/components/Services/Innertube/Parser.bs @@ -4,20 +4,24 @@ import "pkg:/source/utils/StringUtils.bs" namespace Innertube - function ParseResponse(responseData as object, context = invalid as object) as object + function ParseResponseDataForFeeds(responseData as object, context = invalid as object) as object if responseData = invalid return [] end if - containers = GetContainers(responseData) - if containers.Count() = 0 - return [] - end if - if context = invalid context = {} end if + if not ValidBool(context.noContainers) + containers = GetContainers(responseData) + if containers.Count() = 0 + return [] + end if + else + containers = responseData + end if + context.Append({ directives: Innertube.GetParsingDirectives() @@ -38,15 +42,17 @@ namespace Innertube return context.feeds end function - function ParseChannelPageResponse(responseData as object) as object + function ParseChannelPageResponseData(responseData as object) as object if responseData = invalid - return invalid + return { + error: "Invalid response data" + } end if - alert = ObjectUtils.Dig(responseData, ["alerts", 0, "alertRenderer"]) - if IsAssociativeArray(alert) and alert.type = "ERROR" + error = ParseResponseDataForError(responseData) + if error <> "" return { - error: ParseText(alert.text) + error: error } end if @@ -128,7 +134,7 @@ namespace Innertube items = [] continuation = invalid - feeds = ParseResponse(responseData, { "currentAuthor": author, "currentAuthorId": authorId }) + feeds = ParseResponseDataForFeeds(responseData, { "currentAuthor": author, "currentAuthorId": authorId }) if feeds.Count() > 0 items = ValidArray(feeds[0].items) if feeds[0].DoesExist("continuation") @@ -154,15 +160,17 @@ namespace Innertube return channel end function - function ParsePlaylistPageResponse(responseData as object) as object + function ParsePlaylistPageResponseData(responseData as object) as object if responseData = invalid - return invalid + return { + error: "Invalid response data" + } end if - alert = ObjectUtils.Dig(responseData, ["alerts", 0, "alertRenderer"]) - if IsAssociativeArray(alert) and alert.type = "ERROR" + error = ParseResponseDataForError(responseData) + if error <> "" return { - error: ParseText(alert.text) + error: error } end if @@ -205,7 +213,7 @@ namespace Innertube "statsText": statsText } - feeds = ParseResponse(responseData) + feeds = ParseResponseDataForFeeds(responseData) if feeds.Count() > 0 playlist["videos"] = ValidArray(feeds[0].items) if feeds[0].DoesExist("continuation") @@ -216,6 +224,38 @@ namespace Innertube return playlist end function + function ParseResponseDataForError(responseData as object) as string + if responseData = invalid + return "" + end if + + alert = ObjectUtils.Dig(responseData, ["alerts", 0, "alertRenderer"]) + if IsAssociativeArray(alert) and alert.type = "ERROR" + return ParseText(alert.text) + end if + + return "" + end function + + function ParseResponseForCacheControl(response as object) as dynamic + if not response.IsSuccess() + return invalid + end if + + headers = ValidAssociativeArray(response.Headers()) + if headers.DoesExist("cache-control") + return headers["cache-control"] + end if + + json = response.Json() + maxAgeSeconds = ObjectUtils.Dig(json, ["responseContext", "maxAgeSeconds"]) + if IsInt(maxAgeSeconds) + return `max-age=${maxAgeSeconds}` + end if + + return invalid + end function + function GetContainers(responseData as object) as object return [ responseData["contents"] diff --git a/playlet-lib/src/components/Services/Innertube/PlayerEndpoint.bs b/playlet-lib/src/components/Services/Innertube/PlayerEndpoint.bs index deb0194d..61796893 100644 --- a/playlet-lib/src/components/Services/Innertube/PlayerEndpoint.bs +++ b/playlet-lib/src/components/Services/Innertube/PlayerEndpoint.bs @@ -26,13 +26,12 @@ namespace Innertube } request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/player?prettyPrint=false&alt=json", payload) - request.Headers({ + headers = { "accept": "*/*" "accept-language": "*" - "user-agent": INNERTUBE_IOS_USER_AGENT - "x-youtube-client-name": INNERTUBE_IOS_CLIENT_NAME - "x-youtube-client-version": INNERTUBE_IOS_CLIENT_VERSION - }) + } + headers.Append(Innertube.CreateHeaders(Innertube.ClientType.IOS)) + request.Headers(headers) return request end function @@ -40,16 +39,14 @@ namespace Innertube function ParseInnertubePlayerResponse(payload as object) as object if not IsAssociativeArray(payload) return { - Success: false - Error: "Invalid payload" + error: "Invalid payload" } end if playabilityStatus = payload["playabilityStatus"] if not IsAssociativeArray(playabilityStatus) return { - Success: false - Error: "Invalid playability status" + error: "Invalid playability status" } end if @@ -59,22 +56,9 @@ namespace Innertube errorMessage = playabilityStatus["reason"] end if - subreason = ObjectUtils.Dig(playabilityStatus, ["errorScreen", "playerErrorMessageRenderer", "subreason"]) - if IsAssociativeArray(subreason) - subreasonText = "" - runs = subreason["runs"] - if IsArray(runs) - for each rn in runs - text = rn["text"] - if IsString(text) - subreasonText += text - end if - end for - end if - subreason = subreasonText - end if + subreason = ParseText(ObjectUtils.Dig(playabilityStatus, ["errorScreen", "playerErrorMessageRenderer", "subreason"])) - if IsString(subreason) + if subreason <> "" errorMessage += `\n` + subreason end if @@ -83,24 +67,21 @@ namespace Innertube end if return { - Success: false - Error: errorMessage + error: errorMessage } end if videoDetails = payload["videoDetails"] if not IsAssociativeArray(videoDetails) return { - Success: false - Error: "Invalid video details" + error: "Invalid video details" } end if streamingData = payload["streamingData"] if not IsAssociativeArray(streamingData) return { - Success: false - Error: "Invalid streaming data" + error: "Invalid streaming data" } end if @@ -123,10 +104,7 @@ namespace Innertube "recommendedVideos": [] } - return { - Success: true - Metadata: videoInfo - } + return videoInfo end function function ParseStoryboards(payload as object, lengthSeconds as integer) as object diff --git a/playlet-lib/src/components/Services/Innertube/ResolveUrl.bs b/playlet-lib/src/components/Services/Innertube/ResolveUrlEndpoint.bs similarity index 100% rename from playlet-lib/src/components/Services/Innertube/ResolveUrl.bs rename to playlet-lib/src/components/Services/Innertube/ResolveUrlEndpoint.bs diff --git a/playlet-lib/src/components/Services/Innertube/Search.bs b/playlet-lib/src/components/Services/Innertube/SearchEndpoint.bs similarity index 73% rename from playlet-lib/src/components/Services/Innertube/Search.bs rename to playlet-lib/src/components/Services/Innertube/SearchEndpoint.bs index a8bc4bf3..9e72a604 100644 --- a/playlet-lib/src/components/Services/Innertube/Search.bs +++ b/playlet-lib/src/components/Services/Innertube/SearchEndpoint.bs @@ -35,13 +35,26 @@ namespace Innertube response = request.Await() if not response.IsSuccess() - return invalid + return { + error: response.ErrorMessage() + } end if - json = response.Json() - return ParseResponse(json) + feeds = ParseResponseDataForFeeds(response.Json()) + + result = { + feeds: feeds + } + + cacheControl = ParseResponseForCacheControl(response) + if cacheControl <> invalid + result["cache-control"] = cacheControl + end if + + return result end function + ' Not part of search endpoint, but this function is fine here. function SearchSuggestions(query as string, cancellation = invalid as object) as object request = HttpClient.Get("https://suggestqueries.google.com/complete/search?hl=en&gl=US&ds=yt&client=youtube&xssi=t&oe=UTF&q=" + query.EncodeUriComponent()) request.Headers({ @@ -51,7 +64,9 @@ namespace Innertube response = request.Await() if not response.IsSuccess() - return invalid + return { + error: response.ErrorMessage() + } end if text = response.Text() @@ -59,7 +74,9 @@ namespace Innertube parsed = ParseJson(text) if not IsArray(parsed) or parsed.Count() < 2 - return invalid + return { + error: "Failed to parse search suggestions" + } end if parsed = parsed[1] @@ -73,7 +90,16 @@ namespace Innertube suggestions.Push(sugg) end for - return suggestions + result = { + suggestions: suggestions + } + + cacheControl = ParseResponseForCacheControl(response) + if cacheControl <> invalid + result["cache-control"] = cacheControl + end if + + return result end function end namespace diff --git a/playlet-lib/src/components/Services/Invidious/InvidiousService.bs b/playlet-lib/src/components/Services/Invidious/InvidiousService.bs index f5e0698c..1d84067a 100644 --- a/playlet-lib/src/components/Services/Invidious/InvidiousService.bs +++ b/playlet-lib/src/components/Services/Invidious/InvidiousService.bs @@ -111,6 +111,12 @@ namespace Invidious request.Cancellation(cancellation) response = request.Await() + + if not response.IsSuccess() + return { + error: response.ErrorMessage() + } + end if return response.Json() end function @@ -160,7 +166,14 @@ namespace Invidious end function) end if - return request.Await() + response = request.Await() + if not response.IsSuccess() + return { + error: response.ErrorMessage() + } + end if + + return response.Json() end function function GetPlaylist(playlistId as string, index = 0 as integer, continuation = "" as string, cancellation = invalid as object) as object @@ -574,11 +587,16 @@ namespace Invidious } end if - videoMetadata = InnertubeService.GetVideoInfoBatched(json) videoDictionary = {} - for each video in videoMetadata - videoDictionary[video.videoId] = video - end for + + videosMetadata = InnertubeService.GetVideoInfoBatched(json) + if not StringUtils.IsNullOrEmpty(videosMetadata.error) + LogError("Failed to load video metadata", videosMetadata.error) + else + for each video in videosMetadata.videos + videoDictionary[video.videoId] = video + end for + end if for each videoId in json video = videoDictionary[videoId] diff --git a/playlet-lib/src/components/VideoPlayer/VideoContentTask.bs b/playlet-lib/src/components/VideoPlayer/VideoContentTask.bs index 63a34de6..e12b4449 100644 --- a/playlet-lib/src/components/VideoPlayer/VideoContentTask.bs +++ b/playlet-lib/src/components/VideoPlayer/VideoContentTask.bs @@ -21,45 +21,36 @@ function VideoContentTask(input as object) as object backend = preferencesNode["playback.backend"] if backend = "playlet" - response = InnertubeService.GetVideoMetadata(contentNode.videoId, { + metadata = InnertubeService.GetVideoMetadata(contentNode.videoId, { cancellation: m.top.cancellation ctt: loungeServiceNode.ctt }) else - response = service.GetVideoMetadata(contentNode.videoId, { cancellation: m.top.cancellation }) + metadata = service.GetVideoMetadata(contentNode.videoId, { cancellation: m.top.cancellation }) end if if m.top.cancel return invalid end if - metadata = response.Json() - - if not response.IsSuccess() or metadata = invalid - errorMessage = response.ErrorMessage() - knownIssue = `{"error":"This helps protect our community. Learn more"}` - - if errorMessage.InStr(knownIssue) <> -1 - errorMessage = `NOTE: Please see the following link for more information about the error\nhttps://github.com/iBicha/playlet/issues/400\n` + errorMessage - end if - - return { - success: false - error: errorMessage - } - end if - contentNode.title = metadata.title contentNode.secondaryTitle = metadata.author contentNode.live = metadata.liveNow - if IsString(metadata.error) + if metadata.error <> invalid + errorMessage = metadata.error + knownIssue = `{"error":"This helps protect our community. Learn more"}` + + if metadata.error.InStr(knownIssue) <> -1 + errorMessage = `NOTE: Please see the following link for more information about the error\nhttps://github.com/iBicha/playlet/issues/400\n` + errorMessage + end if + ' Adding metadata allows us to play next recommended video after displaying the error contentNode.addFields({ metadata: metadata }) return { success: false - error: metadata.error + error: errorMessage } end if diff --git a/playlet-lib/src/components/VideoPlayerDev/VideoContentTaskDev.bs b/playlet-lib/src/components/VideoPlayerDev/VideoContentTaskDev.bs index 73b2d363..d616b95c 100644 --- a/playlet-lib/src/components/VideoPlayerDev/VideoContentTaskDev.bs +++ b/playlet-lib/src/components/VideoPlayerDev/VideoContentTaskDev.bs @@ -27,21 +27,19 @@ function VideoContentTaskDev(input as object) as object backend = preferencesNode["playback.backend"] if backend = "playlet" - response = InnertubeService.GetVideoMetadata(videoId, { cancellation: m.top.cancellation }) + metadata = InnertubeService.GetVideoMetadata(videoId, { cancellation: m.top.cancellation }) else - response = service.GetVideoMetadata(videoId, { cancellation: m.top.cancellation }) + metadata = service.GetVideoMetadata(videoId, { cancellation: m.top.cancellation }) end if if m.top.cancel return invalid end if - metadata = response.Json() - - if not response.IsSuccess() or metadata = invalid + if metadata.error <> invalid return { success: false - error: response.ErrorMessage() + error: metadata.error } end if diff --git a/playlet-lib/src/components/VideoQueue/VideoQueueViewContentTask.bs b/playlet-lib/src/components/VideoQueue/VideoQueueViewContentTask.bs index eead3bcc..c7c398f1 100644 --- a/playlet-lib/src/components/VideoQueue/VideoQueueViewContentTask.bs +++ b/playlet-lib/src/components/VideoQueue/VideoQueueViewContentTask.bs @@ -60,23 +60,17 @@ function LoadVideoDetail(videoNode as object, service as object, instance as str videoId = videoNode.videoId if backend = "playlet" - response = InnertubeService.GetVideoMetadata(videoId, requestOptions) + metadata = InnertubeService.GetVideoMetadata(videoId, requestOptions) else - response = service.GetVideoMetadata(videoId, requestOptions) + metadata = service.GetVideoMetadata(videoId, requestOptions) end if - metadata = response.Json() - - if not response.IsSuccess() or metadata = invalid - LogError("Failed to load video metadata", response.ErrorMessage()) - if response.StatusCode() = 500 - ' The video is likely not available. - ' We set the title to make sure we don't try to load it again - videoNode.title = "Video not available" - end if + if metadata.error <> invalid + LogError("Failed to load video metadata", metadata.error) + videoNode.title = "Video not available" return false end if InvidiousContent.ToVideoContentNode(videoNode, metadata, instance) - return response.IsCached() + return false end function diff --git a/playlet-lib/src/components/Web/PlayletWebServer/Middleware/DashRouter.bs b/playlet-lib/src/components/Web/PlayletWebServer/Middleware/DashRouter.bs index 01714e92..ca688adc 100644 --- a/playlet-lib/src/components/Web/PlayletWebServer/Middleware/DashRouter.bs +++ b/playlet-lib/src/components/Web/PlayletWebServer/Middleware/DashRouter.bs @@ -29,13 +29,12 @@ namespace Http return true end if - metadataRequest = m.invidiousService.GetVideoMetadata(v) - if not metadataRequest.IsSuccess() - response.Default(metadataRequest.StatusCode(), metadataRequest.ErrorMessage()) + metadata = m.invidiousService.GetVideoMetadata(v) + if metadata.error <> invalid + response.Default(500, metadata.error) return true end if - metadata = metadataRequest.Json() m.dashManifest.invidiousInstance = m.invidiousService.GetInstance() qualityFilter = m.CreateQualityFilter(quality) diff --git a/playlet-lib/src/components/Web/PlayletWebServer/Middleware/PlayletInvidiousBackendRouter.bs b/playlet-lib/src/components/Web/PlayletWebServer/Middleware/PlayletInvidiousBackendRouter.bs index 0d95a5a1..5577e3b2 100644 --- a/playlet-lib/src/components/Web/PlayletWebServer/Middleware/PlayletInvidiousBackendRouter.bs +++ b/playlet-lib/src/components/Web/PlayletWebServer/Middleware/PlayletInvidiousBackendRouter.bs @@ -35,8 +35,14 @@ namespace Http request = context.request response = context.response - feeds = InnertubeService.GetTrending({ type: request.query.type }) - if not IsArray(feeds) or feeds.Count() = 0 + result = InnertubeService.GetTrending({ type: request.query.type }) + if result.error <> invalid + response.Json(result) + response.http_code = 500 + return true + end if + + if not IsArray(result.feeds) or result.feeds.Count() = 0 response.Json({ "error": "Failed to get trending feed" }) @@ -44,7 +50,11 @@ namespace Http return true end if - response.Json(ValidArray(feeds[0].items)) + response.Json(ValidArray(result.feeds[0].items)) + if result.DoesExist("cache-control") + response.headers["cache-control"] = result["cache-control"] + end if + return true end function @@ -60,9 +70,20 @@ namespace Http query = request.query.q - suggestions = InnertubeService.SearchSuggestions(query) - suggestions.query = query - response.Json(suggestions) + result = InnertubeService.SearchSuggestions(query) + if result.error <> invalid + response.Json(result) + response.http_code = 500 + return true + end if + + result.query = query + + if result.DoesExist("cache-control") + response.headers["cache-control"] = result["cache-control"] + end if + + response.Json(result) return true end function @@ -104,8 +125,14 @@ namespace Http options.continuation = continuation end if - feeds = InnertubeService.Search(query, options) - if not IsArray(feeds) or feeds.Count() = 0 + result = InnertubeService.Search(query, options) + if result.error <> invalid + response.Json(result) + response.http_code = 500 + return true + end if + + if not IsArray(result.feeds) or result.feeds.Count() = 0 response.Json({ "error": "Failed to search" }) @@ -113,7 +140,11 @@ namespace Http return true end if - response.Json(feeds[0]) + response.Json(result.feeds[0]) + if result.DoesExist("cache-control") + response.headers["cache-control"] = result["cache-control"] + end if + return true end function @@ -215,16 +246,13 @@ namespace Http videoId = route.Mid("/playlet-invidious-backend/api/v1/videos/".Len()) - playerResponse = InnertubeService.GetVideoMetadata(videoId) - if not playerResponse.IsSuccess() - response.Json({ - "error": playerResponse.ErrorMessage() - }) - response.http_code = playerResponse.StatusCode() - return true + metadata = InnertubeService.GetVideoMetadata(videoId) + response.Json(metadata) + + if metadata.error <> invalid + response.http_code = 500 end if - response.Json(playerResponse.Json()) return true end function @@ -242,10 +270,8 @@ namespace Http end if playlist = InnertubeService.GetPlaylist(playlistId, options) - if playlist = invalid - response.Json({ - "error": "Failed to get playlist" - }) + if playlist.error <> invalid + response.Json(playlist) response.http_code = 500 return true end if @@ -281,15 +307,17 @@ namespace Http if channelAndTab.Count() = 1 channelId = channelAndTab[0] channel = InnertubeService.GetChannel(channelId, options) - if channel = invalid - response.Json({ - "error": "Failed to get channel" - }) + if channel.error <> invalid + response.Json(channel) response.http_code = 500 return true end if response.Json(channel) + if channel.DoesExist("cache-control") + response.headers["cache-control"] = channel["cache-control"] + end if + return true else if channelAndTab.Count() = 2 channelId = channelAndTab[0] @@ -301,10 +329,8 @@ namespace Http end if channel = InnertubeService.GetChannel(channelId, options) - if channel = invalid - response.Json({ - "error": "Failed to get channel" - }) + if channel.error <> invalid + response.Json(channel) response.http_code = 500 return true end if @@ -317,6 +343,9 @@ namespace Http result.continuation = channel.continuation end if response.Json(result) + if channel.DoesExist("cache-control") + response.headers["cache-control"] = channel["cache-control"] + end if else result = { "videos": channel.items @@ -325,6 +354,9 @@ namespace Http result.continuation = channel.continuation end if response.Json(result) + if channel.DoesExist("cache-control") + response.headers["cache-control"] = channel["cache-control"] + end if end if return true diff --git a/playlet-web/src/lib/Api/InvidiousApi.ts b/playlet-web/src/lib/Api/InvidiousApi.ts index 836e5441..7a6d4e7a 100644 --- a/playlet-web/src/lib/Api/InvidiousApi.ts +++ b/playlet-web/src/lib/Api/InvidiousApi.ts @@ -25,7 +25,8 @@ export class InvidiousApi { public async searchSuggestions(query: string) { const url = `${this.instance}/api/v1/search/suggestions?q=${encodeURIComponent(query)}®ion=${this.userCountryCode}`; - return await this.cachedFetch(url, 60 * 60 * 24); + const response = await fetch(url); + return await response.json(); } // need to change this