mirror of
https://github.com/LBRYFoundation/Watch-on-LBRY.git
synced 2025-08-23 17:47:26 +00:00
Merge pull request #127 from DeepDoge/master
Watch on LBRY button also added to the Video player + Some bug fixes
This commit is contained in:
commit
0aa64bb8b2
2 changed files with 196 additions and 108 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) => {
|
||||
|
@ -24,11 +28,14 @@ import { getExtensionSettingsAsync, getSourcePlatfromSettingsFromHostname, getTa
|
|||
Object.assign(settings, Object.fromEntries(Object.entries(changes).map(([key, change]) => [key, change.newValue])))
|
||||
})
|
||||
|
||||
const mountPoint = document.createElement('div')
|
||||
mountPoint.style.display = 'flex'
|
||||
const buttonMountPoint = document.createElement('div')
|
||||
buttonMountPoint.style.display = 'flex'
|
||||
|
||||
function WatchOnLbryButton({ target }: { target?: Target }) {
|
||||
if (!target) return null
|
||||
const playerButtonMountPoint = document.createElement('div')
|
||||
playerButtonMountPoint.style.display = 'flex'
|
||||
|
||||
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 +52,155 @@ 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.button.platformNameText}</span>
|
||||
</a>
|
||||
</div>
|
||||
}
|
||||
|
||||
function updateButton(target: Target | null): void {
|
||||
if (!target) return render(<WatchOnLbryButton />, mountPoint)
|
||||
function WatchOnLbryPlayerButton({ source, target }: { source?: Source, target?: Target }) {
|
||||
if (!target || !source) return null
|
||||
const url = getLbryUrlByTarget(target)
|
||||
|
||||
const sourcePlatform = getSourcePlatfromSettingsFromHostname(new URL(location.href).hostname)
|
||||
if (!sourcePlatform) return render(<WatchOnLbryButton />, mountPoint)
|
||||
|
||||
const mountBefore = document.querySelector(sourcePlatform.htmlQueries.mountButtonBefore[target.type])
|
||||
if (!mountBefore) return render(<WatchOnLbryButton />, mountPoint)
|
||||
|
||||
mountBefore.parentElement?.insertBefore(mountPoint, mountBefore)
|
||||
render(<WatchOnLbryButton target={target} />, mountPoint)
|
||||
return <div style={{ display: 'flex', justifyContent: 'center', flexDirection: 'column' }}>
|
||||
<a href={`${url.href}`} target={target.platform === targetPlatformSettings.app ? '' : '_blank'} role='button'
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
gap: '12px',
|
||||
fontWeight: 'bold',
|
||||
border: '0',
|
||||
color: 'whitesmoke',
|
||||
marginRight: '10px',
|
||||
fontSize: '14px',
|
||||
textDecoration: 'none',
|
||||
...target.platform.button.style?.button,
|
||||
}}
|
||||
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.type === 'channel' ? 'Channel on' : 'Watch on'} {target.platform.button.platformNameText}</span>
|
||||
</a>
|
||||
</div>
|
||||
}
|
||||
|
||||
async function findVideoElementAwait() {
|
||||
const sourcePlatform = getSourcePlatfromSettingsFromHostname(new URL(location.href).hostname)
|
||||
if (!sourcePlatform) throw new Error(`Unknown source of: ${location.href}`)
|
||||
function updateButton(params: { source: Source, target: Target } | null): void {
|
||||
if (!params) {
|
||||
render(<WatchOnLbryButton />, buttonMountPoint)
|
||||
render(<WatchOnLbryPlayerButton />, playerButtonMountPoint)
|
||||
return
|
||||
}
|
||||
|
||||
const mountPlayerButtonBefore = params.source.platform.htmlQueries.mountPoints.mountPlayerButtonBefore ?
|
||||
document.querySelector(params.source.platform.htmlQueries.mountPoints.mountPlayerButtonBefore) :
|
||||
null
|
||||
if (!mountPlayerButtonBefore) render(<WatchOnLbryPlayerButton />, playerButtonMountPoint)
|
||||
else {
|
||||
if (mountPlayerButtonBefore.previousSibling !== playerButtonMountPoint)
|
||||
mountPlayerButtonBefore.parentElement?.insertBefore(playerButtonMountPoint, mountPlayerButtonBefore)
|
||||
render(<WatchOnLbryPlayerButton target={params.target} source={params.source} />, playerButtonMountPoint)
|
||||
}
|
||||
|
||||
const mountButtonBefore = document.querySelector(params.source.platform.htmlQueries.mountPoints.mountButtonBefore[params.source.type])
|
||||
if (!mountButtonBefore) render(<WatchOnLbryButton />, playerButtonMountPoint)
|
||||
else {
|
||||
if (mountButtonBefore.previousSibling !== buttonMountPoint)
|
||||
mountButtonBefore.parentElement?.insertBefore(buttonMountPoint, mountButtonBefore)
|
||||
render(<WatchOnLbryButton target={params.target} source={params.source} />, buttonMountPoint)
|
||||
}
|
||||
}
|
||||
|
||||
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 +218,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 +250,41 @@ 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)
|
||||
if (descriptionElement) {
|
||||
const anchors = Array.from(descriptionElement.querySelectorAll<HTMLAnchorElement>('a'))
|
||||
|
||||
const linksContainer =
|
||||
source.type === 'video' ?
|
||||
document.querySelector(source.platform.htmlQueries.videoDescription) :
|
||||
source.platform.htmlQueries.channelLinks ? document.querySelector(source.platform.htmlQueries.channelLinks) : null
|
||||
|
||||
console.log(linksContainer)
|
||||
|
||||
if (linksContainer) {
|
||||
const anchors = Array.from(linksContainer.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 +292,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,7 @@ const targetPlatform = (o: {
|
|||
displayName: string
|
||||
theme: string
|
||||
button: {
|
||||
text: string
|
||||
platformNameText: string,
|
||||
icon: string
|
||||
style?:
|
||||
{
|
||||
|
@ -80,7 +80,7 @@ export const targetPlatformSettings = {
|
|||
displayName: 'Madiator.com',
|
||||
theme: 'linear-gradient(130deg, #499375, #43889d)',
|
||||
button: {
|
||||
text: 'Watch on',
|
||||
platformNameText: '',
|
||||
icon: chrome.runtime.getURL('assets/icons/lbry/madiator-logo.svg'),
|
||||
style: {
|
||||
button: { flexDirection: 'row-reverse' },
|
||||
|
@ -93,7 +93,7 @@ export const targetPlatformSettings = {
|
|||
displayName: 'Odysee',
|
||||
theme: 'linear-gradient(130deg, #c63d59, #f77937)',
|
||||
button: {
|
||||
text: 'Watch on Odysee',
|
||||
platformNameText: 'Odysee',
|
||||
icon: chrome.runtime.getURL('assets/icons/lbry/odysee-logo.svg')
|
||||
}
|
||||
}),
|
||||
|
@ -102,7 +102,7 @@ export const targetPlatformSettings = {
|
|||
displayName: 'LBRY App',
|
||||
theme: 'linear-gradient(130deg, #499375, #43889d)',
|
||||
button: {
|
||||
text: 'Watch on LBRY',
|
||||
platformNameText: 'LBRY',
|
||||
icon: chrome.runtime.getURL('assets/icons/lbry/lbry-logo.svg')
|
||||
}
|
||||
}),
|
||||
|
@ -113,9 +113,13 @@ export const targetPlatformSettings = {
|
|||
const sourcePlatform = (o: {
|
||||
hostnames: string[]
|
||||
htmlQueries: {
|
||||
mountButtonBefore: Record<ResolveUrlTypes, string>,
|
||||
mountPoints: {
|
||||
mountButtonBefore: Record<ResolveUrlTypes, string>,
|
||||
mountPlayerButtonBefore: string | null,
|
||||
}
|
||||
videoPlayer: string,
|
||||
videoDescription: string
|
||||
channelLinks: string | null
|
||||
}
|
||||
}) => o
|
||||
export type SourcePlatform = ReturnType<typeof sourcePlatform>
|
||||
|
@ -130,24 +134,32 @@ export const sourcePlatfromSettings = {
|
|||
"youtube.com": sourcePlatform({
|
||||
hostnames: ['www.youtube.com'],
|
||||
htmlQueries: {
|
||||
mountButtonBefore: {
|
||||
video: 'ytd-video-owner-renderer~#subscribe-button',
|
||||
channel: '#channel-header-container #buttons'
|
||||
mountPoints: {
|
||||
mountButtonBefore: {
|
||||
video: 'ytd-video-owner-renderer~#subscribe-button',
|
||||
channel: '#channel-header-container #buttons'
|
||||
},
|
||||
mountPlayerButtonBefore: 'ytd-player .ytp-right-controls',
|
||||
},
|
||||
videoPlayer: '#ytd-player video',
|
||||
videoDescription: 'ytd-video-secondary-info-renderer #description'
|
||||
videoDescription: 'ytd-video-secondary-info-renderer #description',
|
||||
channelLinks: '#channel-header #links-holder'
|
||||
}
|
||||
}),
|
||||
"yewtu.be": sourcePlatform({
|
||||
hostnames: ['yewtu.be', 'vid.puffyan.us', 'invidio.xamh.de', 'invidious.kavin.rocks'],
|
||||
htmlQueries: {
|
||||
mountButtonBefore:
|
||||
{
|
||||
video: '#watch-on-youtube',
|
||||
channel: '#subscribe'
|
||||
mountPoints: {
|
||||
mountButtonBefore:
|
||||
{
|
||||
video: '#watch-on-youtube',
|
||||
channel: '#subscribe'
|
||||
},
|
||||
mountPlayerButtonBefore: null,
|
||||
},
|
||||
videoPlayer: '#player-container video',
|
||||
videoDescription: '#descriptionWrapper'
|
||||
videoDescription: '#descriptionWrapper',
|
||||
channelLinks: null
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
Loading…
Add table
Reference in a new issue