mirror of
https://github.com/LBRYFoundation/Watch-on-LBRY.git
synced 2025-08-23 17:47:26 +00:00
🍙 Bug fixes, and other fixes
This commit is contained in:
parent
ca4c486ea7
commit
a6472799a1
2 changed files with 108 additions and 91 deletions
|
@ -13,10 +13,14 @@ import { getExtensionSettingsAsync, getSourcePlatfromSettingsFromHostname, getTa
|
|||
time: number | null
|
||||
}
|
||||
|
||||
const sourcePlatform = getSourcePlatfromSettingsFromHostname(new URL(location.href).hostname)
|
||||
if (!sourcePlatform) return
|
||||
const targetPlatforms = getTargetPlatfromSettingsEntiries()
|
||||
interface Source {
|
||||
platform: SourcePlatform
|
||||
id: string
|
||||
type: ResolveUrlTypes
|
||||
time: number | null
|
||||
}
|
||||
|
||||
const targetPlatforms = getTargetPlatfromSettingsEntiries()
|
||||
const settings = await getExtensionSettingsAsync()
|
||||
// Listen Settings Change
|
||||
chrome.storage.onChanged.addListener(async (changes, areaName) => {
|
||||
|
@ -27,8 +31,8 @@ import { getExtensionSettingsAsync, getSourcePlatfromSettingsFromHostname, getTa
|
|||
const mountPoint = document.createElement('div')
|
||||
mountPoint.style.display = 'flex'
|
||||
|
||||
function WatchOnLbryButton({ target }: { target?: Target }) {
|
||||
if (!target) return null
|
||||
function WatchOnLbryButton({ source, target }: { source?: Source, target?: Target }) {
|
||||
if (!target || !source) return null
|
||||
const url = getLbryUrlByTarget(target)
|
||||
|
||||
return <div style={{ display: 'flex', justifyContent: 'center', flexDirection: 'column' }}>
|
||||
|
@ -45,104 +49,109 @@ import { getExtensionSettingsAsync, getSourcePlatfromSettingsFromHostname, getTa
|
|||
border: '0',
|
||||
color: 'whitesmoke',
|
||||
padding: '10px 16px',
|
||||
marginRight: target.type === 'channel' ? '10px' : '4px',
|
||||
marginRight: source?.type === 'channel' ? '10px' : '4px',
|
||||
fontSize: '14px',
|
||||
textDecoration: 'none',
|
||||
...target.platform.button.style?.button,
|
||||
}}
|
||||
onClick={() => findVideoElementAwait().then((videoElement) => {
|
||||
onClick={() => findVideoElementAwait(source).then((videoElement) => {
|
||||
videoElement.pause()
|
||||
})}
|
||||
>
|
||||
<img src={target.platform.button.icon} height={16}
|
||||
style={{ transform: 'scale(1.5)', ...target.platform.button.style?.icon }} />
|
||||
<span>{target.platform.button.text}</span>
|
||||
<span>{target.type === 'channel' ? 'Channel on' : 'Watch on'} {target.platform.displayName}</span>
|
||||
</a>
|
||||
</div>
|
||||
}
|
||||
|
||||
function updateButton(target: Target | null): void {
|
||||
if (!target) return render(<WatchOnLbryButton />, mountPoint)
|
||||
function updateButton(params: { source: Source, target: Target } | null): void {
|
||||
if (!params) return render(<WatchOnLbryButton />, mountPoint)
|
||||
|
||||
const sourcePlatform = getSourcePlatfromSettingsFromHostname(new URL(location.href).hostname)
|
||||
if (!sourcePlatform) return render(<WatchOnLbryButton />, mountPoint)
|
||||
|
||||
const mountBefore = document.querySelector(sourcePlatform.htmlQueries.mountButtonBefore[target.type])
|
||||
const mountBefore = document.querySelector(params.source.platform.htmlQueries.mountButtonBefore[params.source.type])
|
||||
if (!mountBefore) return render(<WatchOnLbryButton />, mountPoint)
|
||||
|
||||
mountBefore.parentElement?.insertBefore(mountPoint, mountBefore)
|
||||
render(<WatchOnLbryButton target={target} />, mountPoint)
|
||||
render(<WatchOnLbryButton target={params.target} source={params.source} />, mountPoint)
|
||||
}
|
||||
|
||||
async function findVideoElementAwait() {
|
||||
const sourcePlatform = getSourcePlatfromSettingsFromHostname(new URL(location.href).hostname)
|
||||
if (!sourcePlatform) throw new Error(`Unknown source of: ${location.href}`)
|
||||
async function findVideoElementAwait(source: Source) {
|
||||
let videoElement: HTMLVideoElement | null = null
|
||||
while (!(videoElement = document.querySelector(sourcePlatform.htmlQueries.videoPlayer))) await sleep(200)
|
||||
while (!(videoElement = document.querySelector(source.platform.htmlQueries.videoPlayer))) await sleep(200)
|
||||
return videoElement
|
||||
}
|
||||
|
||||
async function getTargetsByURL(...urls: URL[]) {
|
||||
const params: Parameters<typeof requestResolveById>[0] = []
|
||||
const platform = targetPlatformSettings[settings.targetPlatform]
|
||||
async function getSourceByUrl(url: URL): Promise<Source | null> {
|
||||
const platform = getSourcePlatfromSettingsFromHostname(new URL(location.href).hostname)
|
||||
if (!platform) return null
|
||||
|
||||
const datas: Record<string, { url: URL, type: ResolveUrlTypes }> = {}
|
||||
|
||||
for (const url of urls) {
|
||||
if (url.pathname === '/watch' && url.searchParams.has('v')) {
|
||||
const id = url.searchParams.get('v')!
|
||||
const type: ResolveUrlTypes = 'video'
|
||||
params.push({ id, type })
|
||||
datas[id] = { url, type }
|
||||
if (url.pathname === '/watch' && url.searchParams.has('v')) {
|
||||
return {
|
||||
id: url.searchParams.get('v')!,
|
||||
platform,
|
||||
time: url.searchParams.has('t') ? parseYouTubeURLTimeString(url.searchParams.get('t')!) : null,
|
||||
type: 'video'
|
||||
}
|
||||
else if (url.pathname.startsWith('/channel/')) {
|
||||
const id = url.pathname.substring("/channel/".length)
|
||||
const type: ResolveUrlTypes = 'channel'
|
||||
params.push({ id, type })
|
||||
datas[id] = { url, type }
|
||||
}
|
||||
else if (url.pathname.startsWith('/channel/')) {
|
||||
return {
|
||||
id: url.pathname.substring("/channel/".length),
|
||||
platform,
|
||||
time: null,
|
||||
type: 'channel'
|
||||
}
|
||||
else if (url.pathname.startsWith('/c/') || url.pathname.startsWith('/user/')) {
|
||||
// We have to download the page content again because these parts of the page are not responsive
|
||||
// yt front end sucks anyway
|
||||
const content = await (await fetch(location.href)).text()
|
||||
const prefix = `https://www.youtube.com/feeds/videos.xml?channel_id=`
|
||||
const suffix = `"`
|
||||
const startsAt = content.indexOf(prefix) + prefix.length
|
||||
const endsAt = content.indexOf(suffix, startsAt)
|
||||
const id = content.substring(startsAt, endsAt)
|
||||
const type: ResolveUrlTypes = 'channel'
|
||||
params.push({ id, type })
|
||||
datas[id] = { url, type }
|
||||
}
|
||||
else if (url.pathname.startsWith('/c/') || url.pathname.startsWith('/user/')) {
|
||||
// We have to download the page content again because these parts of the page are not responsive
|
||||
// yt front end sucks anyway
|
||||
const content = await (await fetch(location.href)).text()
|
||||
const prefix = `https://www.youtube.com/feeds/videos.xml?channel_id=`
|
||||
const suffix = `"`
|
||||
const startsAt = content.indexOf(prefix) + prefix.length
|
||||
const endsAt = content.indexOf(suffix, startsAt)
|
||||
const id = content.substring(startsAt, endsAt)
|
||||
return {
|
||||
id,
|
||||
platform,
|
||||
time: null,
|
||||
type: 'channel'
|
||||
}
|
||||
}
|
||||
|
||||
const results = Object.entries(await requestResolveById(params))
|
||||
const targets: Record<string, Target | null> = Object.fromEntries(results.map(([id, result]) => {
|
||||
const data = datas[id]
|
||||
return null
|
||||
}
|
||||
|
||||
if (!result) return [
|
||||
data.url.href,
|
||||
null
|
||||
]
|
||||
async function getTargetsBySources(...sources: Source[]) {
|
||||
const params: Parameters<typeof requestResolveById>[0] = sources.map((source) => ({ id: source.id, type: source.type }))
|
||||
const platform = targetPlatformSettings[settings.targetPlatform]
|
||||
|
||||
return [
|
||||
data.url.href,
|
||||
{
|
||||
type: data.type,
|
||||
lbryPathname: result?.id,
|
||||
platform,
|
||||
time: data.type === 'channel' ? null : (data.url.searchParams.has('t') ? parseYouTubeURLTimeString(data.url.searchParams.get('t')!) : null)
|
||||
}
|
||||
]
|
||||
}))
|
||||
const results = await requestResolveById(params)
|
||||
const targets: Record<string, Target | null> = Object.fromEntries(
|
||||
sources.map((source) => {
|
||||
const result = results[source.id]
|
||||
if (!result) return [
|
||||
source.id,
|
||||
null
|
||||
]
|
||||
|
||||
return [
|
||||
source.id,
|
||||
{
|
||||
type: result.type,
|
||||
lbryPathname: result.id,
|
||||
platform,
|
||||
time: source.time
|
||||
}
|
||||
]
|
||||
})
|
||||
)
|
||||
|
||||
return targets
|
||||
}
|
||||
// We should get this from background, so the caching works and we don't get errors in the future if yt decides to impliment CORS
|
||||
async function requestResolveById(...params: Parameters<typeof resolveById>): ReturnType<typeof resolveById> {
|
||||
const json = await new Promise<string | null | 'error'>((resolve) => chrome.runtime.sendMessage({ json: JSON.stringify(params) }, resolve))
|
||||
if (json === 'error')
|
||||
{
|
||||
if (json === 'error') {
|
||||
console.error("Background error on:", params)
|
||||
throw new Error("Background error.")
|
||||
}
|
||||
|
@ -160,24 +169,28 @@ import { getExtensionSettingsAsync, getSourcePlatfromSettingsFromHostname, getTa
|
|||
while (true) {
|
||||
await sleep(500)
|
||||
|
||||
const url: URL = (urlCache?.href === location.href) ? urlCache : new URL(location.href);
|
||||
const url: URL = (urlCache?.href === location.href) ? urlCache : new URL(location.href)
|
||||
const source = await getSourceByUrl(new URL(location.href))
|
||||
if (!source) continue
|
||||
|
||||
try {
|
||||
if (settings.redirect) {
|
||||
const target = (await getTargetsByURL(url))[url.href]
|
||||
const target = (await getTargetsBySources(source))[source.id]
|
||||
if (!target) continue
|
||||
if (url === urlCache) continue
|
||||
|
||||
|
||||
const lbryURL = getLbryUrlByTarget(target)
|
||||
|
||||
findVideoElementAwait().then((videoElement) => {
|
||||
|
||||
// As soon as video play is ready and start playing, pause it.
|
||||
findVideoElementAwait(source).then((videoElement) => {
|
||||
videoElement.addEventListener('play', () => videoElement.pause(), { once: true })
|
||||
videoElement.pause()
|
||||
})
|
||||
|
||||
|
||||
if (target.platform === targetPlatformSettings.app) {
|
||||
if (document.hidden) await new Promise((resolve) => document.addEventListener('visibilitychange', resolve, { once: true }))
|
||||
// Its not gonna be able to replace anyway
|
||||
// This was empty window doesnt stay open
|
||||
// Replace is being used so browser doesnt start an empty window
|
||||
// Its not gonna be able to replace anyway, since its a LBRY Uri
|
||||
location.replace(lbryURL)
|
||||
}
|
||||
else {
|
||||
|
@ -188,30 +201,35 @@ import { getExtensionSettingsAsync, getSourcePlatfromSettingsFromHostname, getTa
|
|||
}
|
||||
else {
|
||||
if (urlCache !== url) updateButton(null)
|
||||
let target = (await getTargetsByURL(url))[url.href]
|
||||
let target = (await getTargetsBySources(source))[source.id]
|
||||
|
||||
// There is no target found via API try to check Video Description for LBRY links.
|
||||
if (!target) {
|
||||
const descriptionElement = document.querySelector(sourcePlatform.htmlQueries.videoDescription)
|
||||
const descriptionElement = document.querySelector(source.platform.htmlQueries.videoDescription)
|
||||
if (descriptionElement) {
|
||||
const anchors = Array.from(descriptionElement.querySelectorAll<HTMLAnchorElement>('a'))
|
||||
|
||||
|
||||
for (const anchor of anchors) {
|
||||
if (!anchor.href) continue
|
||||
const url = new URL(anchor.href)
|
||||
let lbryURL: URL | null = null
|
||||
if (sourcePlatform === sourcePlatfromSettings['youtube.com']) {
|
||||
|
||||
// Extract real link from youtube's redirect link
|
||||
if (source.platform === sourcePlatfromSettings['youtube.com']) {
|
||||
if (!targetPlatforms.some(([key, platform]) => url.searchParams.get('q')?.startsWith(platform.domainPrefix))) continue
|
||||
lbryURL = new URL(url.searchParams.get('q')!)
|
||||
}
|
||||
// Just directly use the link itself on other platforms
|
||||
else {
|
||||
if (!targetPlatforms.some(([key, platform]) => url.href.startsWith(platform.domainPrefix))) continue
|
||||
lbryURL = new URL(url.href)
|
||||
}
|
||||
|
||||
|
||||
if (lbryURL) {
|
||||
target = {
|
||||
lbryPathname: lbryURL.pathname.substring(1),
|
||||
time: null,
|
||||
type: 'video',
|
||||
type: lbryURL.pathname.substring(1).includes('/') ? 'video' : 'channel',
|
||||
platform: targetPlatformSettings[settings.targetPlatform]
|
||||
}
|
||||
break
|
||||
|
@ -219,14 +237,17 @@ import { getExtensionSettingsAsync, getSourcePlatfromSettingsFromHostname, getTa
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (target?.type === 'video') {
|
||||
const videoElement = document.querySelector<HTMLVideoElement>(sourcePlatform.htmlQueries.videoPlayer)
|
||||
if (videoElement) target.time = videoElement.currentTime > 3 && videoElement.currentTime < videoElement.duration - 1 ? videoElement.currentTime : null
|
||||
|
||||
if (!target) updateButton(null)
|
||||
else {
|
||||
// If target is a video target add timestampt to it
|
||||
if (target.type === 'video') {
|
||||
const videoElement = document.querySelector<HTMLVideoElement>(source.platform.htmlQueries.videoPlayer)
|
||||
if (videoElement) target.time = videoElement.currentTime > 3 && videoElement.currentTime < videoElement.duration - 1 ? videoElement.currentTime : null
|
||||
}
|
||||
|
||||
updateButton({ target, source })
|
||||
}
|
||||
|
||||
// We run it anyway with null target to hide the button
|
||||
updateButton(target)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
|
|
|
@ -60,7 +60,6 @@ const targetPlatform = (o: {
|
|||
displayName: string
|
||||
theme: string
|
||||
button: {
|
||||
text: string
|
||||
icon: string
|
||||
style?:
|
||||
{
|
||||
|
@ -80,7 +79,6 @@ export const targetPlatformSettings = {
|
|||
displayName: 'Madiator.com',
|
||||
theme: 'linear-gradient(130deg, #499375, #43889d)',
|
||||
button: {
|
||||
text: 'Watch on',
|
||||
icon: chrome.runtime.getURL('assets/icons/lbry/madiator-logo.svg'),
|
||||
style: {
|
||||
button: { flexDirection: 'row-reverse' },
|
||||
|
@ -93,7 +91,6 @@ export const targetPlatformSettings = {
|
|||
displayName: 'Odysee',
|
||||
theme: 'linear-gradient(130deg, #c63d59, #f77937)',
|
||||
button: {
|
||||
text: 'Watch on Odysee',
|
||||
icon: chrome.runtime.getURL('assets/icons/lbry/odysee-logo.svg')
|
||||
}
|
||||
}),
|
||||
|
@ -102,7 +99,6 @@ export const targetPlatformSettings = {
|
|||
displayName: 'LBRY App',
|
||||
theme: 'linear-gradient(130deg, #499375, #43889d)',
|
||||
button: {
|
||||
text: 'Watch on LBRY',
|
||||
icon: chrome.runtime.getURL('assets/icons/lbry/lbry-logo.svg')
|
||||
}
|
||||
}),
|
||||
|
|
Loading…
Add table
Reference in a new issue