94 lines
3.0 KiB
Plaintext
94 lines
3.0 KiB
Plaintext
import "pkg:/components/Services/Innertube/Constants.bs"
|
|
import "pkg:/source/services/HttpClient.bs"
|
|
import "pkg:/source/utils/Logging.bs"
|
|
import "pkg:/source/utils/ObjectUtils.bs"
|
|
import "pkg:/source/utils/RegistryUtils.bs"
|
|
import "pkg:/source/utils/StringUtils.bs"
|
|
import "pkg:/source/utils/TimeUtils.bs"
|
|
|
|
namespace Innertube
|
|
|
|
const SESSION_DATA_VERSION = 1
|
|
const INNERTUBE_VISITOR_DATA_LIFESPAN_SECONDS = 60 * 60 * 24 * 14 ' 14 days
|
|
|
|
function GetSessionData(cancellation = invalid as object) as object
|
|
sessionData = ReadSessionDataFromRegistry()
|
|
if sessionData <> invalid
|
|
return sessionData
|
|
end if
|
|
|
|
sessionData = RequestSessionData(cancellation)
|
|
SaveSessionDataToRegistry(sessionData)
|
|
return sessionData
|
|
end function
|
|
|
|
function RequestSessionData(cancellation = invalid as object) as object
|
|
request = HttpClient.Get("https://www.youtube.com/sw.js_data")
|
|
request.Headers({
|
|
"Accept-Language": "en-US,en;q=0.9"
|
|
"User-Agent": INNERTUBE_WEB_USER_AGENT
|
|
"Accept": "*/*"
|
|
"Referer": "https://www.youtube.com/sw.js"
|
|
})
|
|
request.Cancellation(cancellation)
|
|
|
|
response = request.Await()
|
|
if not response.IsSuccess()
|
|
LogError("Failed to fetch session data", response.ErrorMessage())
|
|
return invalid
|
|
end if
|
|
|
|
text = response.Text()
|
|
text = text.Replace(`)]}'`, "")
|
|
|
|
json = ParseJson(text)
|
|
if json = invalid
|
|
LogError("Failed to parse session data", text)
|
|
return invalid
|
|
end if
|
|
|
|
visitorData = ObjectUtils.Dig(json, [0, 2, 0, 0, 13])
|
|
if StringUtils.IsNullOrEmpty(visitorData)
|
|
LogError("Visitor data not found", text)
|
|
return invalid
|
|
end if
|
|
|
|
return {
|
|
"timestamp": TimeUtils.Now().AsSeconds()
|
|
"visitorData": visitorData
|
|
}
|
|
end function
|
|
|
|
function SaveSessionDataToRegistry(sessionData as object) as void
|
|
if sessionData = invalid
|
|
return
|
|
end if
|
|
|
|
sessionData.__version = SESSION_DATA_VERSION
|
|
|
|
RegistryUtils.Write(RegistryUtils.INNERTUBE_SESSION_DATA, FormatJson(sessionData))
|
|
end function
|
|
|
|
function ReadSessionDataFromRegistry() as object
|
|
sessionData = RegistryUtils.Read(RegistryUtils.INNERTUBE_SESSION_DATA)
|
|
if StringUtils.IsNullOrEmpty(sessionData)
|
|
return invalid
|
|
end if
|
|
|
|
sessionData = ParseJson(sessionData)
|
|
if sessionData = invalid
|
|
RegistryUtils.Delete(RegistryUtils.INNERTUBE_SESSION_DATA)
|
|
return invalid
|
|
end if
|
|
|
|
timestamp = sessionData.timestamp
|
|
nowSeconds = TimeUtils.Now().AsSeconds()
|
|
if nowSeconds - timestamp > INNERTUBE_VISITOR_DATA_LIFESPAN_SECONDS
|
|
RegistryUtils.Delete(RegistryUtils.INNERTUBE_SESSION_DATA)
|
|
return invalid
|
|
end if
|
|
|
|
return sessionData
|
|
end function
|
|
end namespace
|