Files
playlet-piped/playlet-lib/src/components/Services/Invidious/InvidiousService.bs
T
2024-02-27 20:04:12 -05:00

640 lines
23 KiB
Plaintext

import "pkg:/components/Dialog/DialogUtils.bs"
import "pkg:/components/VideoFeed/PaginationType.bs"
import "pkg:/source/AsyncTask/AsyncTask.bs"
import "pkg:/source/AsyncTask/Tasks.bs"
import "pkg:/source/services/HttpClient.bs"
import "pkg:/source/utils/CryptoUtils.bs"
import "pkg:/source/utils/Logging.bs"
import "pkg:/source/utils/RegistryUtils.bs"
import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/TimeUtils.bs"
namespace Invidious
const INSTANCES_API = "https://api.invidious.io/instances.json?sort_by=type,users"
const DEFAULT_INSTANCE = "https://invidious.fdn.fr"
const TOKEN_CALLBACK = "/invidious/token_callback"
const STATS_ENDPOINT = "/api/v1/stats"
const VIDEOS_ENDPOINT = "/api/v1/videos"
const PLAYLISTS_ENDPOINT = "/api/v1/playlists"
const CHANNELS_ENDPOINT = "/api/v1/channels"
const HISTORY_ENDPOINT = "/api/v1/auth/history"
const SEARCH_SUGGEST_ENDPOINT = "/api/v1/search/suggestions"
const AUTH_SCOPES = "GET:feed,GET:playlists*,POST:tokens/*,:history*,:subscriptions*"
const AUTH_PLAYLISTS = "/api/v1/auth/playlists"
const AUTH_SUBSCRIPTIONS = "/api/v1/auth/subscriptions"
const AUTH_TOKENS_UNREGISTER = "/api/v1/auth/tokens/unregister"
const AUTH_TOKENS_REGISTER = "/api/v1/auth/tokens/register"
const TOKEN_TIMESPAN = 60 * 60 * 24 * 365 * 2 '2 years
const ERROR_NOT_AUTHENTICATED = "Not authenticated"
class InvidiousService
public node as object
function new(node as object)
m.node = node
end function
function GetUserRegion() as string
if m._userRegion = invalid
m._userRegion = m.node.applicationInfo@.GetUserCountryCode()
end if
return m._userRegion
end function
function GetAuthenticationHeaders(token as string) as object
return {
"Authorization": `Bearer ${token}`
}
end function
function GetInstance() as string
if m.preferences = invalid
m.preferences = m.node.preferences
end if
instance = m.preferences["invidious.instance"]
if not StringUtils.IsNullOrEmpty(instance)
return instance
end if
return DEFAULT_INSTANCE
end function
function MarkVideoWatched(videoId as dynamic) as void
if StringUtils.IsNullOrEmpty(videoId)
return
end if
authToken = m.node.authToken
if authToken = invalid
return
end if
url = `${authToken.instance}${Invidious.HISTORY_ENDPOINT}/${videoId}`
request = HttpClient.Post(url, "")
request.Headers(m.GetAuthenticationHeaders(authToken.token))
request.Await()
end function
function SearchSuggestions(q as string, cancellation = invalid as object) as object
instance = m.GetInstance()
url = `${instance}${Invidious.SEARCH_SUGGEST_ENDPOINT}`
request = HttpClient.Get(url)
request.QueryParam("region", m.GetUserRegion())
request.QueryParam("q", q)
request.CacheSeconds(60 * 60 * 24)
request.Cancellation(cancellation)
response = request.Await()
return response.Json()
end function
function GetVideoMetadata(videoId as string, options = invalid as object) as object
' 5 hours cache. Videos should expire in 6 hours, but since we don't
' have the exact expiration time, we'll use 5 hours. Invidious currently
' Does a fresh fetch if the cache is older than 10 minutes.
' https://github.com/iv-org/invidious/blob/069e91d2a609b1df94bdfbb693335969b2a281d8/src/invidious/videos.cr#L349
cacheSeconds = 18000 ' 5 hours
cancellation = invalid
tryCount = 2
if options <> invalid
if options.DoesExist("cacheSeconds")
cacheSeconds = options.cacheSeconds
end if
if options.DoesExist("cancellation")
cancellation = options.cancellation
end if
if options.DoesExist("tryCount")
tryCount = options.tryCount
end if
end if
instance = m.GetInstance()
url = `${instance}${Invidious.VIDEOS_ENDPOINT}/${videoId}`
request = HttpClient.Get(url)
request.CacheSeconds(cacheSeconds)
request.Cancellation(cancellation)
if tryCount > 1
request.TryCount(tryCount)
request.RetryCallback(function(context as object) as boolean
response = context.response
' In some cases, video info requests return "HTTP/0.9 when not allowed" errors.
' Retrying should usually fix the issue.
if response.StatusCode() = HttpClient.CurlErrors.CURLE_UNSUPPORTED_PROTOCOL
errorMessage = response.ErrorMessage()
if errorMessage.InStr("HTTP/0.9") <> -1
return true
end if
end if
return false
end function)
end if
return request.Await()
end function
function GetPlaylist(playlistId as string, index = 0 as integer, cancellation = invalid as object) as object
authToken = m.node.authToken
if authToken = invalid
instance = m.GetInstance()
url = `${instance}${Invidious.PLAYLISTS_ENDPOINT}/${playlistId}`
request = HttpClient.Get(url)
else
url = `${authToken.instance}${Invidious.AUTH_PLAYLISTS}/${playlistId}`
request = HttpClient.Get(url)
request.Headers(m.GetAuthenticationHeaders(authToken.token))
end if
request.QueryParam("index", index)
request.Cancellation(cancellation)
return request.Await()
end function
function GetChannel(authorId as string, cancellation = invalid as object) as object
instance = m.GetInstance()
url = `${instance}${Invidious.CHANNELS_ENDPOINT}/${authorId}`
request = HttpClient.Get(url)
request.Cancellation(cancellation)
request.CacheSeconds(60 * 60 * 24)' 24 hours
request.TryCount(3)
return request.Await()
end function
function GetVideoStreamUrl(videoId as string, itag = invalid as dynamic) as string
instance = m.GetInstance()
url = `${instance}/latest_version?id=${videoId}`
if itag <> invalid
url = `${url}&itag=${itag}`
end if
return url
end function
function MarkFeedPagination(feedContentNode as object) as object
feedSources = feedContentNode.feedSources
feedSourcesIndex = feedContentNode.feedSourcesIndex
feedSource = feedSources[feedSourcesIndex]
if m.endpoints = invalid
m.endpoints = m.node.apiDefinitions
end if
endpoint = m.endpoints[feedSource.endpoint]
if endpoint = invalid or StringUtils.IsNullOrEmpty(endpoint.paginationType)
return feedSource
end if
feedSourceState = feedSource.state
if not feedSourceState.DoesExist("queryParams")
feedSourceState["queryParams"] = {}
end if
feedSourceState.paginationType = endpoint.paginationType
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
feedSources[feedSourcesIndex] = feedSource
feedContentNode.feedSources = feedSources
return feedSource
end function
function MakeRequest(feedSource as object, additionalQueryParams = invalid as object, cancellation = invalid as object) as object
if m.endpoints = invalid
m.endpoints = m.node.apiDefinitions
end if
endpoint = m.endpoints[feedSource.endpoint]
if endpoint = invalid
return {
success: false
error: `Endpoint ${feedSource.endpoint} not found`
}
end if
instance = m.GetInstance()
request = HttpClient.Get(instance + endpoint.url)
if endpoint.authenticated = true
authToken = m.node.authToken
if authToken = invalid
return {
success: false
error: ERROR_NOT_AUTHENTICATED
}
end if
request.Url(authToken.instance + endpoint.url)
request.Headers(m.GetAuthenticationHeaders(authToken.token))
end if
if endpoint.queryParams <> invalid
for each queryParamKey in endpoint.queryParams
queryParam = endpoint.queryParams[queryParamKey]
if queryParam.default <> invalid
if IsString(queryParam.type) and queryParam.type = "#ISO3166"
if queryParam.default = "GetUserCountryCode"
request.QueryParam(queryParamKey, m.node.applicationInfo@.GetUserCountryCode())
else
request.QueryParam(queryParamKey, queryParam.default)
end if
else if IsArray(queryParam.default) and queryParam.arrayType <> invalid
request.QueryParamArray(queryParamKey, queryParam.default, queryParam.arrayType)
else
request.QueryParam(queryParamKey, queryParam.default)
end if
end if
end for
end if
if feedSource.cacheSeconds <> invalid
request.CacheSeconds(feedSource.cacheSeconds)
else if endpoint.cacheSeconds <> invalid
request.CacheSeconds(endpoint.cacheSeconds)
end if
if feedSource.tryCount <> invalid
request.TryCount(feedSource.tryCount)
else if endpoint.tryCount <> invalid
request.TryCount(endpoint.tryCount)
end if
if feedSource.queryParams <> invalid
request.QueryParams(feedSource.queryParams)
end if
if additionalQueryParams <> invalid
request.QueryParams(additionalQueryParams)
end if
if feedSource.pathParams <> invalid
request.PathParams(feedSource.pathParams)
end if
request.Cancellation(cancellation)
response = request.Await()
if m.responseHandlers = invalid
m.responseHandlers = {
DefaultHandler: m.DefaultHandler
AuthFeedHandler: m.AuthFeedHandler
PlaylistHandler: m.PlaylistHandler
VideoInfoHandler: m.VideoInfoHandler
PlaylistInfoHandler: m.PlaylistInfoHandler
ChannelInfoHandler: m.ChannelInfoHandler
ChannelVideosHandler: m.ChannelVideosHandler
ChannelPlaylistsHandler: m.ChannelPlaylistsHandler
WatchHistoryHandler: m.WatchHistoryHandler
}
end if
responseHandler = endpoint.responseHandler <> invalid ? m.responseHandlers[endpoint.responseHandler] : m.responseHandlers["DefaultHandler"]
result = responseHandler(m, feedSource, response)
if response.IsSuccess() and result <> invalid
return {
success: true
result: result
}
else
return {
success: false
error: response.ErrorMessage()
}
end if
end function
function DefaultHandler(m as object, feedSource as object, response as object) as object
if response.StatusCode() = 200
json = response.Json()
return {
items: json
}
end if
return invalid
end function
function PlaylistHandler(m as object, feedSource as object, response as object) as object
if response.StatusCode() = 200
json = response.Json()
return {
items: json.videos
}
end if
return invalid
end function
function ChannelVideosHandler(m as object, feedSource as object, response as object) as object
if response.StatusCode() = 200
json = response.Json()
return {
items: json.videos
continuation: json.continuation
}
end if
return invalid
end function
function ChannelPlaylistsHandler(m as object, feedSource as object, response as object) as object
if response.StatusCode() = 200
json = response.Json()
return {
items: json.playlists
continuation: json.continuation
}
end if
return invalid
end function
function VideoInfoHandler(m as object, feedSource as object, response as object) as object
statusCode = response.StatusCode()
if statusCode >= 500
' In some cases, such as a video became private, or a live stream ended,
' Invidious returns a 500 error. We can in this case return a valid response
' with just a video id, which will allow us to show a valid thumbnail if possible.
' This is to makes it possible to load a bookmarked video and delete it even if
' it is no longer valid.
response.OverrideStatusCode(200)
return {
items: [{
"videoId": feedSource.pathParams.id
"type": "video"
}]
}
end if
if statusCode = 200
json = response.Json()
json.type = "video"
return {
items: [json]
}
end if
return invalid
end function
function PlaylistInfoHandler(m as object, feedSource as object, response as object) as object
if response.StatusCode() = 200
json = response.Json()
json.type = "playlist"
return {
items: [json]
}
end if
return invalid
end function
function ChannelInfoHandler(m as object, feedSource as object, response as object) as object
if response.StatusCode() = 200
json = response.Json()
json.type = "channel"
return {
items: [json]
}
end if
return invalid
end function
function AuthFeedHandler(m as object, feedSource as object, response as object) as object
m.DeleteExpiredToken(response)
if response.StatusCode() <> 200
return invalid
end if
json = response.Json()
if json = invalid
return invalid
end if
videos = []
if IsArray(json.notifications)
videos.Append(json.notifications)
end if
if IsArray(json.videos)
videos.Append(json.videos)
end if
return {
items: videos
}
end function
function WatchHistoryHandler(m as object, feedSource as object, response as object) as object
m.DeleteExpiredToken(response)
if response.StatusCode() <> 200
return invalid
end if
json = response.Json()
if json = invalid
return invalid
end if
videos = []
for each item in json
videos.push({
"type": "video"
"videoId": item
})
end for
return {
items: videos
}
end function
function DeleteExpiredToken(response as object)
if response.StatusCode() = 403
LogWarn(`Invidious instance responded with 403: ${response.Text()}`)
LogWarn("Deleting Invidious token...")
m.DeleteAuthToken()
end if
end function
function GetAuthToken() as object
tokenPayload = RegistryUtils.Read(RegistryUtils.INVIDIOUS_TOKEN)
if tokenPayload = invalid
return invalid
end if
authToken = ParseJson(tokenPayload)
if authToken = invalid or authToken.instance = invalid or authToken.token = invalid
RegistryUtils.Delete(RegistryUtils.INVIDIOUS_TOKEN)
return invalid
end if
if not m.VerifyTokenScope(authToken.token)
' Right now we're probably in a UI thread, and we can't unregister the token
' Without a Task
AsyncTask.Start(Tasks.InvidiousUnregisterTokenTask, {
invidious: m.node
authToken: authToken
})
RegistryUtils.Delete(RegistryUtils.INVIDIOUS_TOKEN)
message = `It looks like you are logged in to Invidious, but your access token does not have the required permissions.
For that reason, we have logged you out. Please log in again.
This can happen when Playlet is updated with new features.
We apologize for the inconvenience.`
DialogUtils.ShowDialog(message, "User logged out")
return invalid
end if
return authToken
end function
function SetAuthToken(token as string, instance as string, username as dynamic)
obj = {
token: token
instance: instance
username: username
}
json = FormatJson(obj)
RegistryUtils.Write(RegistryUtils.INVIDIOUS_TOKEN, json)
m.node.authToken = obj
end function
function VerifyTokenScope(token as string) as boolean
tokenObject = ParseJson(token)
if tokenObject = invalid
LogWarn("Failed to json parse token:", token)
return false
end if
if not IsArray(tokenObject.scopes)
LogWarn("Token scopes are not an array:", tokenObject.scopes)
return false
end if
scopes = tokenObject.scopes.join(",")
expectedScopes = Invidious.AUTH_SCOPES
validScopes = expectedScopes = scopes
if not validScopes
LogWarn(`Token scopes do not match expected scopes. Expected: "${expectedScopes}", got: "${scopes}"`)
end if
return validScopes
end function
function DeleteAuthToken()
m.node.authToken = invalid
RegistryUtils.Delete(RegistryUtils.INVIDIOUS_TOKEN)
end function
function Logout() as boolean
authToken = m.node.authToken
if authToken = invalid
return false
end if
m.UnregisterToken(authToken)
m.DeleteAuthToken()
return true
end function
function UnregisterToken(authToken as object) as void
url = `${authToken.instance}${Invidious.AUTH_TOKENS_UNREGISTER}`
request = HttpClient.Post(url, authToken.token)
request.Headers(m.GetAuthenticationHeaders(authToken.token))
request.Header("Content-Type", "application/json")
request.Await()
end function
function GetAuthorizeTokenLink() as dynamic
instance = m.GetInstance()
' Make sure the host is not on https, because https cannot redirect to http, which is our local server
invidiousHost = instance.Replace("https://", "http://")
address = m.node.webServer@.GetServerAddress()
if address = invalid
return invalid
end if
expire = TimeUtils.Now().AsSeconds() + Invidious.TOKEN_TIMESPAN
callbackUrl = `${address}${Invidious.TOKEN_CALLBACK}?ref=${instance}`.EncodeUriComponent()
scope = `${Invidious.AUTH_SCOPES}`.EncodeUriComponent()
return `${invidiousHost}/authorize_token?scopes=${scope}&callback_url=${callbackUrl}&expire=${expire}`
end function
function GetSubscriptions(cancellation = invalid as object) as object
authToken = m.node.authToken
if authToken = invalid
return invalid
end if
url = `${authToken.instance}${Invidious.AUTH_SUBSCRIPTIONS}`
request = HttpClient.Get(url)
request.Headers(m.GetAuthenticationHeaders(authToken.token))
request.Cancellation(cancellation)
return request.Await()
end function
function Subscribe(channelId as string, cancellation = invalid as object) as object
authToken = m.node.authToken
if authToken = invalid
return invalid
end if
url = `${authToken.instance}${Invidious.AUTH_SUBSCRIPTIONS}/${channelId}`
request = HttpClient.Post(url, "")
request.Headers(m.GetAuthenticationHeaders(authToken.token))
request.Cancellation(cancellation)
return request.Await()
end function
function Unsubscribe(channelId as string, cancellation = invalid as object) as object
authToken = m.node.authToken
if authToken = invalid
return invalid
end if
url = `${authToken.instance}${Invidious.AUTH_SUBSCRIPTIONS}/${channelId}`
request = HttpClient.Delete(url)
request.Headers(m.GetAuthenticationHeaders(authToken.token))
request.Cancellation(cancellation)
return request.Await()
end function
end class
end namespace