Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Shiba 2022-08-10 10:14:38 +00:00
commit c0304c1b79
11 changed files with 228 additions and 205 deletions

View file

@ -68,6 +68,7 @@ export function Dialogs(params: { manager: ReturnType<typeof createDialogManager
{` {`
.alert-dialog .alert-dialog
{ {
position: fixed;
border: none; border: none;
background: var(--color-dark); background: var(--color-dark);
color: var(--color-light); color: var(--color-light);

View file

@ -1,25 +1,21 @@
// This should only work in background // This should only work in background
let db: IDBDatabase | null = null
if (typeof chrome.extension === 'undefined') throw new Error("YT urlCache can only be accessed from extension windows and service-workers.") if (typeof chrome.extension === 'undefined') throw new Error("YT urlCache can only be accessed from extension windows and service-workers.")
if (typeof self.indexedDB !== 'undefined') { let db = new Promise<IDBDatabase>((resolve, reject) => {
const openRequest = indexedDB.open("yt-url-resolver-cache") if (typeof self.indexedDB !== 'undefined') {
openRequest.addEventListener('upgradeneeded', () => openRequest.result.createObjectStore("store").createIndex("expireAt", "expireAt")) const openRequest = indexedDB.open("yt-url-resolver-cache")
openRequest.addEventListener('upgradeneeded', () => openRequest.result.createObjectStore("store").createIndex("expireAt", "expireAt"))
// Delete Expired openRequest.addEventListener('success', () => {
openRequest.addEventListener('success', () => { resolve(openRequest.result)
db = openRequest.result clearExpired()
clearExpired() }, { once: true })
}) }
} else reject(`IndexedDB not supported`)
else console.warn(`IndexedDB not supported`) })
async function clearExpired() { async function clearExpired() {
return new Promise<void>((resolve, reject) => { return new Promise<void>(async (resolve, reject) => {
if (!db) throw new Error(`IDBDatabase not defined.`) const transaction = (await db).transaction("store", "readwrite")
const transaction = db.transaction("store", "readwrite")
const range = IDBKeyRange.upperBound(new Date()) const range = IDBKeyRange.upperBound(new Date())
const expireAtCursorRequest = transaction.objectStore("store").index("expireAt").openCursor(range) const expireAtCursorRequest = transaction.objectStore("store").index("expireAt").openCursor(range)
@ -40,8 +36,8 @@ async function clearExpired() {
} }
async function clearAll() { async function clearAll() {
return await new Promise<void>((resolve, reject) => { return await new Promise<void>(async (resolve, reject) => {
const store = db?.transaction("store", "readwrite").objectStore("store") const store = (await db).transaction("store", "readwrite").objectStore("store")
if (!store) return resolve() if (!store) return resolve()
const request = store.clear() const request = store.clear()
request.addEventListener('success', () => resolve()) request.addEventListener('success', () => resolve())
@ -50,8 +46,8 @@ async function clearAll() {
} }
async function put(url: string | null, id: string): Promise<void> { async function put(url: string | null, id: string): Promise<void> {
return await new Promise((resolve, reject) => { return await new Promise(async (resolve, reject) => {
const store = db?.transaction("store", "readwrite").objectStore("store") const store = (await db).transaction("store", "readwrite").objectStore("store")
if (!store) return resolve() if (!store) return resolve()
const expireAt = !url ? new Date(Date.now() + 1 * 60 * 60 * 1000) : new Date(Date.now() + 15 * 24 * 60 * 60 * 1000) const expireAt = !url ? new Date(Date.now() + 1 * 60 * 60 * 1000) : new Date(Date.now() + 15 * 24 * 60 * 60 * 1000)
const request = store.put({ value: url, expireAt }, id) const request = store.put({ value: url, expireAt }, id)
@ -65,8 +61,8 @@ async function put(url: string | null, id: string): Promise<void> {
// null means there is cache of that id has no lbrypathname // null means there is cache of that id has no lbrypathname
// undefined means there is no cache // undefined means there is no cache
async function get(id: string): Promise<string | null | undefined> { async function get(id: string): Promise<string | null | undefined> {
const response = (await new Promise((resolve, reject) => { const response = (await new Promise(async (resolve, reject) => {
const store = db?.transaction("store", "readonly").objectStore("store") const store = (await db).transaction("store", "readonly").objectStore("store")
if (!store) return reject(`Can't find object store.`) if (!store) return reject(`Can't find object store.`)
const request = store.get(id) const request = store.get(id)

View file

@ -49,7 +49,7 @@ export async function resolveById(params: Paramaters, progressCallback?: (progre
const controller = new AbortController() const controller = new AbortController()
// 5 second timeout: // 5 second timeout:
const timeoutId = setTimeout(() => controller.abort(), 5000) const timeoutId = setTimeout(() => controller.abort(), 15000)
const apiResponse = await fetch(url.toString(), { cache: 'no-store', signal: controller.signal }) const apiResponse = await fetch(url.toString(), { cache: 'no-store', signal: controller.signal })
clearTimeout(timeoutId) clearTimeout(timeoutId)

View file

@ -1,6 +0,0 @@
# Getting your subscription data
1. Go to https://takeout.google.com/settings/takeout
2. Deselect everything except `YouTube and YouTube Music` and within that only select `subscriptions`
3. Go through the process and create the export
4. Once it's exported, open the archive and find `YouTube and YouTube Music/subscriptions/subscriptions.json` and upload it to the extension

View file

@ -4,7 +4,6 @@ import { getFileContent } from '../../modules/file'
import { getSubsFromCsv, getSubsFromJson, getSubsFromOpml } from '../../modules/yt' import { getSubsFromCsv, getSubsFromJson, getSubsFromOpml } from '../../modules/yt'
import { resolveById } from '../../modules/yt/urlResolve' import { resolveById } from '../../modules/yt/urlResolve'
import { targetPlatformSettings, useExtensionSettings } from '../../settings' import { targetPlatformSettings, useExtensionSettings } from '../../settings'
import readme from './README.md'
async function getSubscribedChannelIdsFromFile(file: File) { async function getSubscribedChannelIdsFromFile(file: File) {
const ext = file.name.split('.').pop()?.toLowerCase() const ext = file.name.split('.').pop()?.toLowerCase()
@ -71,8 +70,15 @@ function YTtoLBRY() {
<Conversion /> <Conversion />
<aside class="help"> <aside class="help">
<iframe allowFullScreen <iframe allowFullScreen
src='https://lbry.tv/$/embed/howtouseconverter/c9827448d6ac7a74ecdb972c5cdf9ddaf648a28e' /> src='https://odysee.com/$/embed/convert-subscriptions-from-YouTube-to-LBRY/36f3a010295afe1c55e91b63bcb2eabc028ec86c?r=8bgP4hEdbd9jwBJmhEaqP3dD75LzsUob' />
<section dangerouslySetInnerHTML={{ __html: readme }} /> <section><h1 id="getting-your-subscription-data">Getting your subscription data</h1>
<ol>
<li>Go to <a href="https://takeout.google.com/settings/takeout" target='_blank'>https://takeout.google.com/settings/takeout</a></li>
<li>Deselect everything except <code>YouTube and YouTube Music</code> and within that only select <code>subscriptions</code></li>
<li>Go through the process and create the export</li>
<li>Once it's exported, open the archive and find <code>YouTube and YouTube Music/subscriptions/subscriptions.(json/csv/opml)</code> and upload it to the extension</li>
</ol>
</section>
</aside> </aside>
</main> </main>
} }

View file

@ -5,12 +5,12 @@ import { lbryUrlCache } from '../../modules/yt/urlCache'
import { setExtensionSetting, targetPlatformSettings, useExtensionSettings } from '../../settings' import { setExtensionSetting, targetPlatformSettings, useExtensionSettings } from '../../settings'
function WatchOnLbryPopup(params: {}) { function WatchOnLbryPopup(params: {}) {
const { redirect, videoSubButton, channelSubButton, videoPlayerButton } = useExtensionSettings() const { redirectChannel, redirectVideo, redirectVideoPlaylist, buttonVideoSub, buttonChannelSub, buttonVideoPlayer } = useExtensionSettings()
let [loading, updateLoading] = useState(() => false) let [loading, updateLoading] = useState(() => false)
let [route, updateRoute] = useState<string>(() => '')
const dialogManager = createDialogManager() const dialogManager = createDialogManager()
async function loads<T>(operation: Promise<T>) { async function loads<T>(operation: Promise<T>) {
try { try {
updateLoading(true) updateLoading(true)
@ -27,67 +27,66 @@ function WatchOnLbryPopup(params: {}) {
<Dialogs manager={dialogManager} /> <Dialogs manager={dialogManager} />
{ {
<header> <header>
<section> <img id="logo" src={targetPlatformSettings.odysee.button.icon}></img>
<img id="logo" src={targetPlatformSettings.odysee.button.icon}></img> <label>Watch on Odysee</label>
<label>Watch on Odysee</label>
</section>
</header> </header>
} }
{ {
<main> <main>
<section> <section>
<label>Pick a mode</label> <label>Auto redirect when:</label>
<div className='options'> <div className='options'>
<a onClick={() => setExtensionSetting('redirect', true)} className={`button ${redirect ? 'active' : ''}`}> <div class="toggle-option">
Redirect <span>Playing a video</span>
</a> <a onClick={() => setExtensionSetting('redirectVideo', !redirectVideo)} className={`button ${redirectVideo ? 'active' : ''}`}>
<a onClick={() => setExtensionSetting('redirect', false)} className={`button ${redirect ? '' : 'active'}`}> {redirectVideo ? 'Active' : 'Deactive'}
Show a button
</a> </a>
</div> </div>
</section> <div class="toggle-option">
{ <span>Playing a playlist</span>
!redirect && <a onClick={() => setExtensionSetting('redirectVideoPlaylist', !redirectVideoPlaylist)} className={`button ${redirectVideoPlaylist ? 'active' : ''}`}>
<section> {redirectVideoPlaylist ? 'Active' : 'Deactive'}
<label>Show button at:</label> </a>
<b className='filled'>Video</b> </div>
<div className='options'> <div class="toggle-option">
<div className="left"> <span>Viewing a channel</span>
<span>Subscribe Button:</span> <a onClick={() => setExtensionSetting('redirectChannel', !redirectChannel)} className={`button ${redirectChannel ? 'active' : ''}`}>
</div> {redirectChannel ? 'Active' : 'Deactive'}
<a onClick={() => setExtensionSetting('videoSubButton', !videoSubButton)} className={`button ${videoSubButton ? 'active' : ''}`}> </a>
{videoSubButton ? 'Active' : 'Deactive'} </div>
</a> </div>
</div> </section>
<div className='options'>
<div className="left">
<span>Video Player:</span>
</div>
<a onClick={() => setExtensionSetting('videoPlayerButton', !videoPlayerButton)} className={`button ${videoPlayerButton ? 'active' : ''}`}>
{videoPlayerButton ? 'Active' : 'Deactive'}
</a>
</div>
<b className='filled'>Channel</b>
<div className='options'>
<div className="left">
<span>Subscribe Button:</span>
</div>
<a onClick={() => setExtensionSetting('channelSubButton', !channelSubButton)} className={`button ${channelSubButton ? 'active' : ''}`}>
{channelSubButton ? 'Active' : 'Deactive'}
</a>
</div>
</section>
}
<section> <section>
<a onClick={() => loads(lbryUrlCache.clearAll().then(() => dialogManager.alert("Cleared Cache!")))} className={`button active`}> <label>Show redirect button on:</label>
Clear Resolver Cache <div className='options'>
</a> <div className="toggle-option">
<span>Video Page</span>
<a onClick={() => setExtensionSetting('buttonVideoSub', !buttonVideoSub)} className={`button ${buttonVideoSub ? 'active' : ''}`}>
{buttonVideoSub ? 'Active' : 'Deactive'}
</a>
</div>
<div className="toggle-option">
<span>Channel Page</span>
<a onClick={() => setExtensionSetting('buttonChannelSub', !buttonChannelSub)} className={`button ${buttonChannelSub ? 'active' : ''}`}>
{buttonChannelSub ? 'Active' : 'Deactive'}
</a>
</div>
<div className="toggle-option">
<span>Video Player</span>
<a onClick={() => setExtensionSetting('buttonVideoPlayer', !buttonVideoPlayer)} className={`button ${buttonVideoPlayer ? 'active' : ''}`}>
{buttonVideoPlayer ? 'Active' : 'Deactive'}
</a>
</div>
</div>
</section> </section>
<section> <section>
<label>Tools</label> <label>Tools</label>
<a target='_blank' href='/pages/YTtoLBRY/index.html' className={`filled`}> <a target='_blank' href='/pages/YTtoLBRY/index.html' className={`filled`}>
Subscription Converter Subscription Converter
</a> </a>
<a onClick={() => loads(lbryUrlCache.clearAll().then(() => dialogManager.alert("Cleared Cache!")))} className={`button active`}>
Clear Resolver Cache
</a>
</section> </section>
</main> </main>
} }

View file

@ -1,3 +1,10 @@
#popup {
width: 40em;
max-width: 100%;
overflow: hidden;
margin: auto;
}
header { header {
display: grid; display: grid;
gap: .5em; gap: .5em;
@ -5,11 +12,13 @@ header {
position: sticky; position: sticky;
top: 0; top: 0;
background: rgba(19, 19, 19, 0.5); background: rgba(19, 19, 19, 0.5);
justify-items: center; justify-content: center;
grid-auto-flow: column;
align-items: center;
} }
#logo { #logo {
width: 5em; width: 3em;
} }
main { main {
@ -25,7 +34,7 @@ section {
gap: .75em; gap: .75em;
} }
section>label { label {
font-size: 1.75em; font-size: 1.75em;
font-weight: bold; font-weight: bold;
text-align: center; text-align: center;
@ -41,13 +50,6 @@ section>* {
padding: 0 1rem; padding: 0 1rem;
} }
#popup {
width: 35em;
max-width: 100%;
overflow: hidden;
margin: auto;
}
.center { .center {
display: grid; display: grid;
place-items: center; place-items: center;
@ -58,4 +60,9 @@ section>* {
justify-items: start; justify-items: start;
align-items: center; align-items: center;
text-align: left; text-align: left;
}
.toggle-option {
display: grid;
gap: .5em;
} }

View file

@ -11,8 +11,8 @@ chrome.runtime.onMessage.addListener(({ method, data }, sender, sendResponse) =>
switch (method) { switch (method) {
case 'openTab': case 'openTab':
{ {
const { href, active }: { href: string, active: boolean } = JSON.parse(data) const { href }: { href: string } = JSON.parse(data)
chrome.tabs.create({ url: href, active }) chrome.tabs.create({ url: href, active: sender.tab?.active, index: sender.tab ? sender.tab.index + 1 : undefined })
} }
break break
case 'resolveUrl': case 'resolveUrl':
@ -23,7 +23,7 @@ chrome.runtime.onMessage.addListener(({ method, data }, sender, sendResponse) =>
console.log('lbrypathname request', params, await promise) console.log('lbrypathname request', params, await promise)
resolve(await promise) resolve(await promise)
} catch (error) { } catch (error) {
sendResponse(`error:${(error as any).toString()}`) sendResponse(`error: ${(error as any).toString()}`)
console.error(error) console.error(error)
} }
finally { finally {

View file

@ -17,6 +17,7 @@ import { getExtensionSettingsAsync, getSourcePlatfromSettingsFromHostname, getTa
platform: SourcePlatform platform: SourcePlatform
id: string id: string
type: ResolveUrlTypes type: ResolveUrlTypes
url: URL
time: number | null time: number | null
} }
@ -26,7 +27,6 @@ import { getExtensionSettingsAsync, getSourcePlatfromSettingsFromHostname, getTa
chrome.storage.onChanged.addListener(async (changes, areaName) => { chrome.storage.onChanged.addListener(async (changes, areaName) => {
if (areaName !== 'local') return if (areaName !== 'local') return
Object.assign(settings, Object.fromEntries(Object.entries(changes).map(([key, change]) => [key, change.newValue]))) Object.assign(settings, Object.fromEntries(Object.entries(changes).map(([key, change]) => [key, change.newValue])))
if (settings.redirect) updateButton(null)
}) })
const buttonMountPoint = document.createElement('div') const buttonMountPoint = document.createElement('div')
@ -112,7 +112,7 @@ import { getExtensionSettingsAsync, getSourcePlatfromSettingsFromHostname, getTa
</div> </div>
} }
function updateButton(params: { source: Source, target: Target } | null): void { function updateButtons(params: { source: Source, target: Target } | null): void {
if (!params) { if (!params) {
render(<WatchOnLbryButton />, buttonMountPoint) render(<WatchOnLbryButton />, buttonMountPoint)
render(<WatchOnLbryPlayerButton />, playerButtonMountPoint) render(<WatchOnLbryPlayerButton />, playerButtonMountPoint)
@ -120,7 +120,7 @@ import { getExtensionSettingsAsync, getSourcePlatfromSettingsFromHostname, getTa
} }
{ {
const mountPlayerButtonBefore = settings.videoPlayerButton ? const mountPlayerButtonBefore = settings.buttonVideoPlayer ?
document.querySelector(params.source.platform.htmlQueries.mountPoints.mountPlayerButtonBefore) : document.querySelector(params.source.platform.htmlQueries.mountPoints.mountPlayerButtonBefore) :
null null
if (!mountPlayerButtonBefore) render(<WatchOnLbryPlayerButton />, playerButtonMountPoint) if (!mountPlayerButtonBefore) render(<WatchOnLbryPlayerButton />, playerButtonMountPoint)
@ -134,7 +134,7 @@ import { getExtensionSettingsAsync, getSourcePlatfromSettingsFromHostname, getTa
} }
{ {
const mountButtonBefore = settings[(`${params.source.type}SubButton`) as 'videoSubButton' | 'channelSubButton'] ? const mountButtonBefore = settings[(`button${params.source.type[0].toUpperCase() + params.source.type.substring(1)}Sub`) as 'buttonVideoSub' | 'buttonChannelSub'] ?
document.querySelector(params.source.platform.htmlQueries.mountPoints.mountButtonBefore[params.source.type]) : document.querySelector(params.source.platform.htmlQueries.mountPoints.mountButtonBefore[params.source.type]) :
null null
if (!mountButtonBefore) render(<WatchOnLbryButton />, buttonMountPoint) if (!mountButtonBefore) render(<WatchOnLbryButton />, buttonMountPoint)
@ -163,7 +163,8 @@ import { getExtensionSettingsAsync, getSourcePlatfromSettingsFromHostname, getTa
id: url.searchParams.get('v')!, id: url.searchParams.get('v')!,
platform, platform,
time: url.searchParams.has('t') ? parseYouTubeURLTimeString(url.searchParams.get('t')!) : null, time: url.searchParams.has('t') ? parseYouTubeURLTimeString(url.searchParams.get('t')!) : null,
type: 'video' type: 'video',
url
} }
} }
else if (url.pathname.startsWith('/channel/')) { else if (url.pathname.startsWith('/channel/')) {
@ -171,7 +172,8 @@ import { getExtensionSettingsAsync, getSourcePlatfromSettingsFromHostname, getTa
id: url.pathname.substring("/channel/".length), id: url.pathname.substring("/channel/".length),
platform, platform,
time: null, time: null,
type: 'channel' type: 'channel',
url
} }
} }
else if (url.pathname.startsWith('/c/') || url.pathname.startsWith('/user/')) { else if (url.pathname.startsWith('/c/') || url.pathname.startsWith('/user/')) {
@ -187,7 +189,8 @@ import { getExtensionSettingsAsync, getSourcePlatfromSettingsFromHostname, getTa
id, id,
platform, platform,
time: null, time: null,
type: 'channel' type: 'channel',
url
} }
} }
@ -226,14 +229,53 @@ import { getExtensionSettingsAsync, getSourcePlatfromSettingsFromHostname, getTa
const response = await new Promise<string | null | 'error'>((resolve) => chrome.runtime.sendMessage({ method: 'resolveUrl', data: JSON.stringify(params) }, resolve)) const response = await new Promise<string | null | 'error'>((resolve) => chrome.runtime.sendMessage({ method: 'resolveUrl', data: JSON.stringify(params) }, resolve))
if (response?.startsWith('error:')) { if (response?.startsWith('error:')) {
console.error("Background error on:", params) console.error("Background error on:", params)
throw new Error(`Background error.${response ?? ''}`) throw new Error(`Background error. ${response ?? ''}`)
} }
console.log(response)
return response ? JSON.parse(response) : null return response ? JSON.parse(response) : null
} }
// Request new tab // Request new tab
async function openNewTab(url: URL, active: boolean) { async function openNewTab(url: URL) {
chrome.runtime.sendMessage({ method: 'openTab', data: JSON.stringify({ href: url.href, active }) }) chrome.runtime.sendMessage({ method: 'openTab', data: JSON.stringify({ href: url.href }) })
}
function findTargetFromSourcePage(source: Source): Target | null {
const linksContainer =
source.type === 'video' ?
document.querySelector(source.platform.htmlQueries.videoDescription) :
source.platform.htmlQueries.channelLinks ? document.querySelector(source.platform.htmlQueries.channelLinks) : null
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
// 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) {
return {
lbryPathname: lbryURL.pathname.substring(1),
time: null,
type: lbryURL.pathname.substring(1).includes('/') ? 'video' : 'channel',
platform: targetPlatformSettings[settings.targetPlatform]
}
}
}
}
return null
} }
function getLbryUrlByTarget(target: Target) { function getLbryUrlByTarget(target: Target) {
@ -243,98 +285,72 @@ import { getExtensionSettingsAsync, getSourcePlatfromSettingsFromHostname, getTa
return url return url
} }
let urlHrefCache: string | null = null
while (true) { // Master Loop
for (
let url = new URL(location.href),
urlHrefCache: string | null = null;
;
urlHrefCache = url.href,
url = new URL(location.href)
) {
await sleep(500) await sleep(500)
const url: URL = new URL(location.href) try {
await (async () => {
const source = await getSourceByUrl(new URL(location.href)) const source = await getSourceByUrl(new URL(location.href))
if (!source) return if (!source) {
updateButtons(null)
try { continue
if (settings.redirect) { }
const target = (await getTargetsBySources(source))[source.id] const target = (await getTargetsBySources(source))[source.id] ?? findTargetFromSourcePage(source)
if (!target) return if (!target) {
console.log(url.href, urlHrefCache) updateButtons(null)
if (url.href === urlHrefCache) return continue
const lbryURL = getLbryUrlByTarget(target)
if (source.type === 'video') {
// 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()
})
}
console.log('open', lbryURL.href)
openNewTab(lbryURL, document.hasFocus())
if (window.history.length === 1) window.close()
else window.history.back()
}
else {
if (urlHrefCache !== url.href) updateButton(null)
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 linksContainer =
source.type === 'video' ?
document.querySelector(source.platform.htmlQueries.videoDescription) :
source.platform.htmlQueries.channelLinks ? document.querySelector(source.platform.htmlQueries.channelLinks) : null
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
// 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: lbryURL.pathname.substring(1).includes('/') ? 'video' : 'channel',
platform: targetPlatformSettings[settings.targetPlatform]
}
break
}
}
}
}
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 })
}
}
} catch (error) {
console.error(error)
} }
})()
urlHrefCache = url.href // Update Buttons
if (urlHrefCache !== url.href) updateButtons(null)
// 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
}
updateButtons({ target, source })
// Redirect
if (
source.type === target.type &&
(
(
settings.redirectVideo &&
source.type === 'video' && !source.url.searchParams.has('list')
) ||
(
settings.redirectVideoPlaylist &&
source.type === 'video' && source.url.searchParams.has('list')
) ||
(
settings.redirectChannel &&
source.type === 'channel'
)
)
) {
if (url.href === urlHrefCache) continue
const lbryURL = getLbryUrlByTarget(target)
if (source.type === 'video') {
findVideoElementAwait(source).then((videoElement) => videoElement.pause())
}
openNewTab(lbryURL)
if (window.history.length === 1)
window.close()
else
window.history.back()
}
} catch (error) {
console.error(error)
}
} }
})() })()

View file

@ -21,13 +21,13 @@ async function initSettings() {
if (!Object.keys(targetPlatformSettings).includes(settings.targetPlatform)) setExtensionSetting('targetPlatform', DEFAULT_SETTINGS.targetPlatform) if (!Object.keys(targetPlatformSettings).includes(settings.targetPlatform)) setExtensionSetting('targetPlatform', DEFAULT_SETTINGS.targetPlatform)
if (!Object.keys(ytUrlResolversSettings).includes(settings.urlResolver)) setExtensionSetting('urlResolver', DEFAULT_SETTINGS.urlResolver) if (!Object.keys(ytUrlResolversSettings).includes(settings.urlResolver)) setExtensionSetting('urlResolver', DEFAULT_SETTINGS.urlResolver)
chromeAction.setBadgeText({ text: settings.redirect ? 'ON' : 'OFF' }) // chromeAction.setBadgeText({ text: settings.redirect ? 'ON' : 'OFF' })
} }
chrome.storage.onChanged.addListener((changes, areaName) => { /* chrome.storage.onChanged.addListener((changes, areaName) => {
if (areaName !== 'local' || !changes.redirect) return if (areaName !== 'local' || !changes.redirect) return
chromeAction.setBadgeText({ text: changes.redirect.newValue ? 'ON' : 'OFF' }) chromeAction.setBadgeText({ text: changes.redirect.newValue ? 'ON' : 'OFF' })
}) }) */
chrome.runtime.onStartup.addListener(initSettings) chrome.runtime.onStartup.addListener(initSettings)
chrome.runtime.onInstalled.addListener(initSettings) chrome.runtime.onInstalled.addListener(initSettings)

View file

@ -2,22 +2,26 @@ import type { JSX } from "preact"
import { useEffect, useReducer } from "preact/hooks" import { useEffect, useReducer } from "preact/hooks"
import type { ResolveUrlTypes } from "../modules/yt/urlResolve" import type { ResolveUrlTypes } from "../modules/yt/urlResolve"
export interface ExtensionSettings { export interface ExtensionSettings extends Record<string, string | number | boolean | null | undefined> {
redirect: boolean
targetPlatform: TargetPlatformName targetPlatform: TargetPlatformName
urlResolver: YTUrlResolverName, urlResolver: YTUrlResolverName,
videoSubButton: boolean redirectVideo: boolean,
videoPlayerButton: boolean redirectChannel: boolean,
channelSubButton: boolean redirectVideoPlaylist: boolean,
buttonVideoSub: boolean
buttonVideoPlayer: boolean
buttonChannelSub: boolean
} }
export const DEFAULT_SETTINGS: ExtensionSettings = { export const DEFAULT_SETTINGS: ExtensionSettings = {
redirect: true,
targetPlatform: 'odysee', targetPlatform: 'odysee',
urlResolver: 'odyseeApi', urlResolver: 'odyseeApi',
videoSubButton: true, redirectVideo: false,
videoPlayerButton: true, redirectChannel: false,
channelSubButton: true, redirectVideoPlaylist: false,
buttonVideoSub: true,
buttonVideoPlayer: true,
buttonChannelSub: true,
} }
export function getExtensionSettingsAsync(): Promise<ExtensionSettings> { export function getExtensionSettingsAsync(): Promise<ExtensionSettings> {