Compare commits

...

61 commits

Author SHA1 Message Date
github-actions[bot]
60735f9507
docs(README): update contributors 2023-10-12 20:22:54 +00:00
kodxana
8c26ae0872
Merge pull request #139 from DeepDoge/master
Little clean up and fixes
2022-10-06 19:01:02 +02:00
Shiba
6ba1a373a9
🍣 max-width on popup removed
was causing some issues with exotic browsers
2022-10-01 12:18:34 +03:00
Shiba
c1b53d90a1
Merge branch 'LBRYFoundation:master' into master 2022-09-28 14:39:34 +03:00
Shiba
529931c43b 🍙 removed console.log s 2022-09-28 14:38:37 +03:00
kodxana
351ca5c6c3
Up Version 2022-09-02 13:19:07 +02:00
Shiba
ca65a0288d 🍣 some little fixes in the code
- nothing changed, just some little fixes
2022-08-10 10:18:04 +00:00
kodxana
309806605f
Merge pull request #134 from DeepDoge/master
Major changes
2022-08-10 11:50:01 +02:00
Shiba
7fa57b9e88 🍙 updated YTtoLBRY video 2022-08-10 09:38:57 +00:00
Shiba
21f6ffc85b 🍤 popup width made larger 2022-08-10 08:17:55 +00:00
Shiba
1ee722b6ff 🍣 improved logic of redrect and opening a new tab 2022-08-10 08:12:04 +00:00
Shiba
28ef256c40 🍙 on redirect pause the video directly only 2022-08-10 07:56:24 +00:00
Shiba
a41b51e454 🍣 handle unexpected location.replace behavior 2022-08-09 22:44:40 +00:00
Shiba
5c9910dff1 Merge branch 'master' of https://github.com/DeepDoge/Watch-on-LBRY 2022-08-09 22:22:34 +00:00
Shiba
59a5e0dee2 🍙 on redirect use replace if tab has no history 2022-08-09 22:22:25 +00:00
Shiba
e4fdc4e831
Merge branch 'LBRYFoundation:master' into master 2022-08-10 00:17:05 +03:00
Shiba
9c26d553f5 🍣 major changes
- modes are removed
- added more options for redirect
- extension badge removed
2022-08-09 21:16:05 +00:00
kodxana
f9c70dd90d
Merge pull request #133 from DeepDoge/master
Bug fixes again
2022-08-09 23:15:47 +02:00
Shiba
9ed962df96 Merge branch 'master' of https://github.com/DeepDoge/Watch-on-LBRY 2022-08-09 19:10:43 +00:00
Shiba
a95b46bf0c 🍙 made url resovler timeout longer 2022-08-09 19:10:37 +00:00
Shiba
913282290e
Merge branch 'LBRYFoundation:master' into master 2022-08-09 22:00:41 +03:00
Shiba
6af354de0c 🍙 more bug fixes 2022-08-09 17:49:16 +00:00
Shiba
15f03b3bcc 🍙 removed debug logs 2022-08-09 17:06:41 +00:00
kodxana
64570b83bf
Merge pull request #132 from DeepDoge/master
Opening new tabs handled by the background now
2022-08-09 18:58:29 +02:00
Shiba
4295dbe1fe 🍣 bug fixes 2022-08-09 16:49:45 +00:00
Shiba
619d66d6aa Merge branch 'master' of https://github.com/DeepDoge/Watch-on-LBRY 2022-08-09 16:42:58 +00:00
Shiba
b26d540a4a 🍣 bug fixes 2022-08-09 16:42:51 +00:00
Shiba
32290e5f63
Merge branch 'LBRYFoundation:master' into master 2022-08-09 13:32:27 +03:00
Shiba
c089de3f0f Merge branch 'master' of https://github.com/DeepDoge/Watch-on-LBRY 2022-08-09 10:31:55 +00:00
Shiba
fcdc5cb77a 🍙 opening new tabs handled by the background now
- because firefox seem to block content script from openning new tabs in some cases
2022-08-09 10:31:48 +00:00
kodxana
e0d514916e
Merge pull request #131 from DeepDoge/master
Added option for where to show the buttons
2022-08-08 00:00:17 +02:00
Shiba
376c7b185a
Merge branch 'LBRYFoundation:master' into master 2022-08-07 13:30:46 +03:00
Shiba
73147fdbcd Merge branch 'master' of https://github.com/DeepDoge/Watch-on-LBRY 2022-08-07 10:30:14 +00:00
Shiba
9edd318a35 🍙 added option for where to show the buttons 2022-08-07 10:30:06 +00:00
kodxana
f5c0fc450b
Merge pull request #130 from DeepDoge/master
Removed `tabs` permission
2022-08-06 22:24:43 +02:00
Shiba
259582cd3e
Merge branch 'LBRYFoundation:master' into master 2022-08-06 21:05:33 +03:00
Shiba
38f2d42404 removed tabs permission 2022-08-06 18:04:45 +00:00
kodxana
7b585b27a9
Merge pull request #129 from DeepDoge/master
Added timeout to resolver API request
2022-07-28 14:08:01 +02:00
Shiba
6721966e5b 🍙 added timeout to resolver api request 2022-07-27 06:43:58 +00:00
kodxana
f087d0d1e5
Merge pull request #128 from DeepDoge/master
Button changes
2022-07-26 10:59:34 +02:00
Shiba
de43b990f2 🍣 button changes 2022-07-25 23:25:33 +00:00
Shiba
8f88dbebe7 🍙 little bug fix 2022-07-25 21:44:14 +00:00
kodxana
0aa64bb8b2
Merge pull request #127 from DeepDoge/master
Watch on LBRY button also added to the Video player + Some bug fixes
2022-07-25 22:47:40 +02:00
Shiba
f4dd0306fc
Merge branch 'LBRYFoundation:master' into master 2022-07-25 10:41:07 +03:00
Shiba
29c9b2829a 🍣 New button on the video player 2022-07-24 23:18:34 +00:00
Shiba
a6472799a1 🍙 Bug fixes, and other fixes 2022-07-24 20:41:51 +00:00
kodxana
1f29fc7c29
Merge pull request #125 from DeepDoge/master
Made yt video pause, since we use new tab now
2022-07-08 23:24:19 +02:00
Shiba
ca4c486ea7 Merge branch 'master' of https://github.com/DeepDoge/Watch-on-LBRY 2022-07-07 18:00:38 +00:00
Shiba
4102177212 🍣 Some more bug fixes 2022-07-07 18:00:32 +00:00
Shiba
da8dee83f9
Merge branch 'LBRYFoundation:master' into master 2022-07-07 20:43:33 +03:00
Shiba
ce11d4fdf3 🍣 little bug fix 2022-07-07 17:37:57 +00:00
Shiba
1eb21eb51f 🍙 made yt video pause, since we use new tab now 2022-07-06 13:10:32 +00:00
kodxana
a0577b4530
Merge pull request #123 from DeepDoge/master
New stuff and some changes
2022-07-02 17:33:17 +02:00
Shiba
c895d53253 🍙 new stuff and some changes
- channel buttons and redirect
- in button mode if there is no target try to find lbry url in the description
- used a loop in content script instead of events and stuff to make it less confusing
2022-07-02 15:15:36 +00:00
kodxana
66cb8ccccf
Merge pull request #122 from DeepDoge/master
Some changes
2022-07-01 23:13:02 +02:00
Shiba
f072c95051 🍤 Build for manifest v2 and v3 at once
- and zip them
2022-07-01 20:39:13 +00:00
Shiba
0ba4efd43e 🍙 New button style with gradient 2022-07-01 20:37:03 +00:00
Shiba
066c400cce 🍣 Bug fixes and small changes 2022-07-01 20:34:53 +00:00
kodxana
63a251c0ae
Merge pull request #120 from DeepDoge/master
💩 Upgraded to manifest v3
2022-05-02 17:11:36 +02:00
Shiba
be310e6cb1 🧀 added manifest v2 support for firefox 2022-05-02 13:17:58 +00:00
Shiba
cebdf480fe 💩 upgraded to manifest v3 2022-05-02 12:12:11 +00:00
23 changed files with 743 additions and 506 deletions

1
.gitignore vendored
View file

@ -1,5 +1,6 @@
.cache
dist
build
node_modules
web-ext-artifacts
yarn-error.log

View file

@ -111,7 +111,7 @@ Please make sure to update tests as appropriate.
</tr>
<tr>
<td align="center" style="word-wrap: break-word; width: 150.0; height: 150.0">
<a href=https://github.com/53jk1>
<a href=https://github.com/kbakdev>
<img src=https://avatars.githubusercontent.com/u/56700396?v=4 width="100;" style="border-radius:50%;align-items:center;justify-content:center;overflow:hidden;padding-top:10px" alt=Kacper Bąk/>
<br />
<sub style="font-size:14px"><b>Kacper Bąk</b></sub>

5
global.d.ts vendored
View file

@ -1,4 +1,9 @@
declare module '*.md' {
var _: string
export default _
}
declare namespace chrome
{
export const action = chrome.browserAction
}

56
manifest.v2.json Normal file
View file

@ -0,0 +1,56 @@
{
"manifest_version": 2,
"name": "Watch on LBRY",
"version": "2.0.1",
"icons": {
"16": "assets/icons/wol/icon16.png",
"48": "assets/icons/wol/icon48.png",
"128": "assets/icons/wol/icon128.png"
},
"permissions": [
"https://www.youtube.com/",
"https://yewtu.be/",
"https://vid.puffyan.us/",
"https://invidio.xamh.de/",
"https://invidious.kavin.rocks/",
"https://api.odysee.com/",
"https://lbry.tv/",
"https://odysee.com/",
"https://madiator.com/",
"https://finder.madiator.com/",
"tabs",
"storage"
],
"web_accessible_resources": [
"pages/popup/index.html",
"pages/YTtoLBRY/index.html",
"pages/import/index.html",
"assets/icons/lbry/lbry-logo.svg",
"assets/icons/lbry/odysee-logo.svg",
"assets/icons/lbry/madiator-logo.svg"
],
"browser_action": {
"default_title": "Watch on LBRY",
"default_popup": "pages/popup/index.html"
},
"content_scripts": [
{
"matches": [
"https://www.youtube.com/*",
"https://yewtu.be/*",
"https://vid.puffyan.us/*",
"https://invidio.xamh.de/*",
"https://invidious.kavin.rocks/*"
],
"js": [
"scripts/ytContent.js"
]
}
],
"background": {
"scripts": [
"service-worker-entry-point.js"
],
"persistent": true
}
}

View file

@ -1,7 +1,17 @@
{
"manifest_version": 3,
"name": "Watch on LBRY",
"version": "2.0.0",
"version": "2.0.1",
"icons": {
"16": "assets/icons/wol/icon16.png",
"48": "assets/icons/wol/icon48.png",
"128": "assets/icons/wol/icon128.png"
},
"permissions": [
"storage",
"tabs"
],
"host_permissions": [
"https://www.youtube.com/",
"https://yewtu.be/",
"https://vid.puffyan.us/",
@ -11,10 +21,24 @@
"https://lbry.tv/",
"https://odysee.com/",
"https://madiator.com/",
"https://finder.madiator.com/",
"tabs",
"storage"
"https://finder.madiator.com/"
],
"web_accessible_resources": [{
"resources": [
"pages/popup/index.html",
"pages/YTtoLBRY/index.html",
"pages/import/index.html",
"assets/icons/lbry/lbry-logo.svg",
"assets/icons/lbry/odysee-logo.svg",
"assets/icons/lbry/madiator-logo.svg"
],
"matches": ["<all_urls>"],
"extension_ids": []
}],
"action": {
"default_title": "Watch on LBRY",
"default_popup": "pages/popup/index.html"
},
"content_scripts": [
{
"matches": [
@ -30,28 +54,6 @@
}
],
"background": {
"scripts": [
"settings/background.js",
"scripts/background.js"
],
"persistent": true
},
"browser_action": {
"default_title": "Watch on LBRY",
"default_popup": "pages/popup/index.html"
},
"web_accessible_resources": [
"pages/popup/index.html",
"pages/YTtoLBRY/index.html",
"pages/import/index.html",
"assets/icons/lbry/lbry-logo.svg",
"assets/icons/lbry/odysee-logo.svg",
"assets/icons/lbry/madiator-logo.svg"
],
"icons": {
"16": "assets/icons/wol/icon16.png",
"48": "assets/icons/wol/icon48.png",
"128": "assets/icons/wol/icon128.png"
},
"manifest_version": 2
"service_worker": "service-worker-entry-point.js"
}
}

97
package-lock.json generated
View file

@ -4826,91 +4826,6 @@
"timsort": "^0.3.0"
}
},
"css-loader": {
"version": "6.7.1",
"resolved": "https://registry.npmjs.org/css-loader/-/css-loader-6.7.1.tgz",
"integrity": "sha512-yB5CNFa14MbPJcomwNh3wLThtkZgcNyI2bNMRt8iE5Z8Vwl7f8vQXFAzn2HDOJvtDq2NTZBUGMSUNNyrv3/+cw==",
"dev": true,
"requires": {
"icss-utils": "^5.1.0",
"postcss": "^8.4.7",
"postcss-modules-extract-imports": "^3.0.0",
"postcss-modules-local-by-default": "^4.0.0",
"postcss-modules-scope": "^3.0.0",
"postcss-modules-values": "^4.0.0",
"postcss-value-parser": "^4.2.0",
"semver": "^7.3.5"
},
"dependencies": {
"nanoid": {
"version": "3.3.3",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.3.tgz",
"integrity": "sha512-p1sjXuopFs0xg+fPASzQ28agW1oHD7xDsd9Xkf3T15H3c/cifrFHVwrh74PdoklAPi+i7MdRsE47vm2r6JoB+w==",
"dev": true
},
"postcss": {
"version": "8.4.13",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.13.tgz",
"integrity": "sha512-jtL6eTBrza5MPzy8oJLFuUscHDXTV5KcLlqAWHl5q5WYRfnNRGSmOZmOZ1T6Gy7A99mOZfqungmZMpMmCVJ8ZA==",
"dev": true,
"requires": {
"nanoid": "^3.3.3",
"picocolors": "^1.0.0",
"source-map-js": "^1.0.2"
}
},
"postcss-modules-extract-imports": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/postcss-modules-extract-imports/-/postcss-modules-extract-imports-3.0.0.tgz",
"integrity": "sha512-bdHleFnP3kZ4NYDhuGlVK+CMrQ/pqUm8bx/oGL93K6gVwiclvX5x0n76fYMKuIGKzlABOy13zsvqjb0f92TEXw==",
"dev": true
},
"postcss-modules-local-by-default": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/postcss-modules-local-by-default/-/postcss-modules-local-by-default-4.0.0.tgz",
"integrity": "sha512-sT7ihtmGSF9yhm6ggikHdV0hlziDTX7oFoXtuVWeDd3hHObNkcHRo9V3yg7vCAY7cONyxJC/XXCmmiHHcvX7bQ==",
"dev": true,
"requires": {
"icss-utils": "^5.0.0",
"postcss-selector-parser": "^6.0.2",
"postcss-value-parser": "^4.1.0"
}
},
"postcss-modules-scope": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/postcss-modules-scope/-/postcss-modules-scope-3.0.0.tgz",
"integrity": "sha512-hncihwFA2yPath8oZ15PZqvWGkWf+XUfQgUGamS4LqoP1anQLOsOJw0vr7J7IwLpoY9fatA2qiGUGmuZL0Iqlg==",
"dev": true,
"requires": {
"postcss-selector-parser": "^6.0.4"
}
},
"postcss-modules-values": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/postcss-modules-values/-/postcss-modules-values-4.0.0.tgz",
"integrity": "sha512-RDxHkAiEGI78gS2ofyvCsu7iycRv7oqw5xMWn9iMoR0N/7mf9D50ecQqUo5BZ9Zh2vH4bCUR/ktCqbB9m8vJjQ==",
"dev": true,
"requires": {
"icss-utils": "^5.0.0"
}
},
"postcss-value-parser": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz",
"integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==",
"dev": true
},
"semver": {
"version": "7.3.7",
"resolved": "https://registry.npmjs.org/semver/-/semver-7.3.7.tgz",
"integrity": "sha512-QlYTucUYOews+WeEujDoEGziz4K6c47V/Bd+LjSSYcA94p+DmINdf7ncaUinThfvZyu13lN9OY1XDxt8C0Tw0g==",
"dev": true,
"requires": {
"lru-cache": "^6.0.0"
}
}
}
},
"css-modules-loader-core": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/css-modules-loader-core/-/css-modules-loader-core-1.1.0.tgz",
@ -7923,12 +7838,6 @@
"integrity": "sha1-Bupvg2ead0njhs/h/oEq5dsiPe0=",
"dev": true
},
"icss-utils": {
"version": "5.1.0",
"resolved": "https://registry.npmjs.org/icss-utils/-/icss-utils-5.1.0.tgz",
"integrity": "sha512-soFhflCVWLfRNOPU3iv5Z9VUdT44xFRbzjLsEzSr5AQmgqPMTHdU3PMT1Cf1ssx8fLNJDA1juftYl+PUcv3MqA==",
"dev": true
},
"ieee754": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",
@ -14965,12 +14874,6 @@
"integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=",
"dev": true
},
"source-map-js": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.0.2.tgz",
"integrity": "sha512-R0XvVJ9WusLiqTCEiGCmICCMplcCkIwwR11mOSD9CR5u+IXYdiseeEuXCVAjS54zqwkLcPNnmU4OeJ6tUrWhDw==",
"dev": true
},
"source-map-resolve": {
"version": "0.5.3",
"resolved": "https://registry.npmjs.org/source-map-resolve/-/source-map-resolve-0.5.3.tgz",

View file

@ -8,8 +8,16 @@
"build:parcel": "cross-env NODE_ENV=production parcel build --no-source-maps --no-minify \"src/**/*.{js,jsx,ts,tsx}\" \"src/**/*.html\" \"src/**/*.md\"",
"watch:parcel": "parcel watch --no-hmr --no-source-maps \"src/**/*.{js,jsx,ts,tsx}\" \"src/**/*.html\" \"src/**/*.md\"",
"build:webext": "web-ext build --source-dir ./dist --overwrite-dest",
"build": "npm-run-all -l -p build:parcel build:assets",
"watch": "npm-run-all -l -p watch:parcel watch:assets",
"clear:dist": "rm -r ./dist ; mkdir ./dist",
"build:base": "npm-run-all -l -p build:parcel build:assets",
"pick:manifest:v2": "cp -b ./manifest.v2.json ./dist/manifest.json",
"pick:manifest:v3": "cp -b ./manifest.v3.json ./dist/manifest.json",
"build:v2": "npm run clear:dist ; npm run build:base && npm run pick:manifest:v2",
"build:v3": "npm run clear:dist ; npm run build:base && npm run pick:manifest:v3",
"build": "rm -r ./build ; mkdir ./build && npm run build:v2 && zip -r ./build/manifest-v2.zip ./dist && npm run build:v3 && zip -r ./build/manifest-v3.zip ./dist",
"watch:v2": "npm run clear:dist ; npm run pick:manifest:v2 && npm-run-all -l -p watch:parcel watch:assets",
"watch:v3": "npm run clear:dist ; npm run pick:manifest:v3 && npm-run-all -l -p watch:parcel watch:assets",
"watch": "npm run watch:v3",
"start:chrome": "web-ext run -t chromium --source-dir ./dist",
"start:firefox": "web-ext run --source-dir ./dist",
"test": "jest"

View file

@ -46,11 +46,6 @@ export function createDialogManager() {
}
}
interface DialogElement extends HTMLDivElement {
open: boolean
showModal(): void
}
export function Dialogs(params: { manager: ReturnType<typeof createDialogManager> }) {
const alerts = params.manager.useAlerts()
let currentAlert = Object.values(alerts)[0]
@ -60,7 +55,7 @@ export function Dialogs(params: { manager: ReturnType<typeof createDialogManager
let cancelled = false
const dialog = useRef(null as any as DialogElement)
const dialog = useRef(null as any as HTMLDialogElement)
useEffect(() => {
if (!dialog.current) return
if (!dialog.current.open) dialog.current.showModal()
@ -73,6 +68,7 @@ export function Dialogs(params: { manager: ReturnType<typeof createDialogManager
{`
.alert-dialog
{
position: fixed;
border: none;
background: var(--color-dark);
color: var(--color-light);

View file

@ -1,10 +1,10 @@
import path from 'path'
import { DialogManager } from '../../components/dialogs'
import type { DialogManager } from '../../components/dialogs'
import { getExtensionSettingsAsync, setExtensionSetting, ytUrlResolversSettings } from "../../settings"
import { getFileContent } from '../file'
async function generateKeys() {
const keys = await window.crypto.subtle.generateKey(
const keys = await crypto.subtle.generateKey(
{
name: "RSASSA-PKCS1-v1_5",
// Consider using a 4096-bit key for systems that require long-term security
@ -23,7 +23,7 @@ async function generateKeys() {
}
async function exportPrivateKey(key: CryptoKey) {
const exported = await window.crypto.subtle.exportKey(
const exported = await crypto.subtle.exportKey(
"pkcs8",
key
)
@ -34,7 +34,7 @@ const publicKeyPrefix = `MEwwDQYJKoZIhvcNAQEBBQADOwAwOAIxA`
const publicKeySuffix = `IDAQAB` //`wIDAQAB` `WIDAQAB`
const publicKeyLength = 65
async function exportPublicKey(key: CryptoKey) {
const exported = await window.crypto.subtle.exportKey(
const exported = await crypto.subtle.exportKey(
"spki",
key
)
@ -43,7 +43,7 @@ async function exportPublicKey(key: CryptoKey) {
}
function importPrivateKey(base64: string) {
return window.crypto.subtle.importKey(
return crypto.subtle.importKey(
"pkcs8",
Buffer.from(base64, 'base64'),
{
@ -56,7 +56,7 @@ function importPrivateKey(base64: string) {
}
export async function sign(data: string, privateKey: string) {
return Buffer.from(await window.crypto.subtle.sign(
return Buffer.from(await crypto.subtle.sign(
{ name: "RSASSA-PKCS1-v1_5" },
await importPrivateKey(privateKey),
await crypto.subtle.digest({ name: 'SHA-1' }, Buffer.from(data))
@ -70,22 +70,18 @@ export function resetProfileSettings() {
async function apiRequest<T extends object>(method: 'GET' | 'POST', pathname: string, data: T) {
const settings = await getExtensionSettingsAsync()
/* const urlResolverSettings = ytUrlResolversSettings[settings.urlResolver]
if (!urlResolverSettings.signRequest) throw new Error() */
const url = new URL(ytUrlResolversSettings.madiatorFinder.href/* urlResolverSettings.href */)
const url = new URL(ytUrlResolversSettings.madiatorFinder.href)
url.pathname = path.join(url.pathname, pathname)
url.searchParams.set('data', JSON.stringify(data))
if (true/* requiresSignature */) {
if (!settings.privateKey || !settings.publicKey)
throw new Error('There is no profile.')
if (!settings.privateKey || !settings.publicKey)
throw new Error('There is no profile.')
url.searchParams.set('keys', JSON.stringify({
signature: await sign(url.searchParams.toString(), settings.privateKey!),
publicKey: settings.publicKey
}))
}
url.searchParams.set('keys', JSON.stringify({
signature: await sign(url.searchParams.toString(), settings.privateKey!),
publicKey: settings.publicKey
}))
const respond = await fetch(url.href, { method })

View file

@ -1,4 +1,3 @@
interface YtExportedJsonSubscription {
id: string
etag: string

View file

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

View file

@ -1,12 +1,13 @@
import { chunk } from "lodash"
import path from "path"
import { getExtensionSettingsAsync, ytUrlResolversSettings } from "../../settings"
import { getExtensionSettingsAsync, SourcePlatform, ytUrlResolversSettings } from "../../settings"
import { sign } from "../crypto"
import { LbryPathnameCache } from "./urlCache"
import { lbryUrlCache } from "./urlCache"
const QUERY_CHUNK_SIZE = 100
export type YtUrlResolveItem = { type: 'video' | 'channel', id: string }
export type ResolveUrlTypes = 'video' | 'channel'
export type YtUrlResolveItem = { type: ResolveUrlTypes, id: string }
type Results = Record<string, YtUrlResolveItem>
type Paramaters = YtUrlResolveItem[]
@ -27,7 +28,7 @@ export async function resolveById(params: Paramaters, progressCallback?: (progre
// Check for cache first, add them to the results if there are any cache
// And remove them from the params, so we dont request for them
params = (await Promise.all(params.map(async (item) => {
const cachedLbryUrl = await LbryPathnameCache.get(item.id)
const cachedLbryUrl = await lbryUrlCache.get(item.id)
// Cache can be null, if there is no lbry url yet
if (cachedLbryUrl !== undefined) {
@ -52,13 +53,18 @@ export async function resolveById(params: Paramaters, progressCallback?: (progre
publicKey
}))
const apiResponse = await fetch(url.toString(), { cache: 'no-store' })
const controller = new AbortController()
// 5 second timeout:
const timeoutId = setTimeout(() => controller.abort(), 15000)
const apiResponse = await fetch(url.toString(), { cache: 'no-store', signal: controller.signal })
clearTimeout(timeoutId)
if (apiResponse.ok) {
const response: ApiResponse = await apiResponse.json()
for (const item of params) {
const lbryUrl = (item.type === 'channel' ? response.data.channels : response.data.videos)?.[item.id]?.replaceAll('#', ':') ?? null
// we cache it no matter if its null or not
await LbryPathnameCache.put(lbryUrl, item.id)
await lbryUrlCache.put(lbryUrl, item.id)
if (lbryUrl) results[item.id] = { id: lbryUrl, type: item.type }
}

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 { resolveById } from '../../modules/yt/urlResolve'
import { targetPlatformSettings, useExtensionSettings } from '../../settings'
import readme from './README.md'
async function getSubscribedChannelIdsFromFile(file: File) {
const ext = file.name.split('.').pop()?.toLowerCase()
@ -71,8 +70,15 @@ function YTtoLBRY() {
<Conversion />
<aside class="help">
<iframe allowFullScreen
src='https://lbry.tv/$/embed/howtouseconverter/c9827448d6ac7a74ecdb972c5cdf9ddaf648a28e' />
<section dangerouslySetInnerHTML={{ __html: readme }} />
src='https://odysee.com/$/embed/convert-subscriptions-from-YouTube-to-LBRY/36f3a010295afe1c55e91b63bcb2eabc028ec86c?r=8bgP4hEdbd9jwBJmhEaqP3dD75LzsUob' />
<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>
</main>
}

View file

@ -3,6 +3,21 @@ import { useState } from 'preact/hooks'
import { createDialogManager, Dialogs } from '../../components/dialogs'
import { importProfileKeysFromFile, inputKeyFile } from '../../modules/crypto'
export async function openImportPopup() {
const importPopupWindow = open(
'/pages/import/index.html',
'Import Profile',
[
`height=${Math.max(document.body.clientHeight, screen.height * .5)}`,
`width=${document.body.clientWidth}`,
`toolbar=0,menubar=0,location=0`,
`top=${screenY}`,
`left=${screenX}`
].join(','))
close()
importPopupWindow?.focus()
}
function ImportPage() {
const [loading, updateLoading] = useState(() => false)

View file

@ -2,8 +2,9 @@ import { h, render } from 'preact'
import { useState } from 'preact/hooks'
import { createDialogManager, Dialogs } from '../../components/dialogs'
import { exportProfileKeysAsFile, friendlyPublicKey, generateProfileAndSetNickname, getProfile, purgeProfile, resetProfileSettings } from '../../modules/crypto'
import { LbryPathnameCache } from '../../modules/yt/urlCache'
import { lbryUrlCache } from '../../modules/yt/urlCache'
import { getTargetPlatfromSettingsEntiries, getYtUrlResolversSettingsEntiries, setExtensionSetting, useExtensionSettings } from '../../settings'
import { openImportPopup } from '../import/main'
/** Gets all the options for redirect destinations as selection options */
@ -11,9 +12,9 @@ const targetPlatforms = getTargetPlatfromSettingsEntiries()
const ytUrlResolverOptions = getYtUrlResolversSettingsEntiries()
function WatchOnLbryPopup(params: { profile: Awaited<ReturnType<typeof getProfile>> | null }) {
const { redirect, targetPlatform, urlResolver, privateKey, publicKey } = useExtensionSettings()
const { targetPlatform, urlResolver, redirectChannel, redirectVideo, redirectVideoPlaylist, buttonVideoSub, buttonChannelSub, buttonVideoPlayer, privateKey, publicKey } = useExtensionSettings()
let [loading, updateLoading] = useState(() => false)
let [route, updateRoute] = useState<string | null>(() => null)
let [route, updateRoute] = useState<string>(() => '')
const dialogManager = createDialogManager()
const nickname = params.profile ? params.profile.nickname ?? 'No Nickname' : '...'
@ -31,47 +32,33 @@ function WatchOnLbryPopup(params: { profile: Awaited<ReturnType<typeof getProfil
}
}
async function importButtonClick() {
const importPopupWindow = open(
'/pages/import/index.html',
'Import Profile',
[
`height=${Math.max(document.body.clientHeight, screen.height * .5)}`,
`width=${document.body.clientWidth}`,
`toolbar=0,menubar=0,location=0`,
`top=${screenY}`,
`left=${screenX}`
].join(','))
close()
importPopupWindow?.focus()
}
return <div id='popup'>
<Dialogs manager={dialogManager} />
{
publicKey
? <header>
<header>
{
publicKey &&
<section>
<label>{nickname}</label>
<p>{friendlyPublicKey(publicKey)}</p>
<span><b>Score: {params.profile?.score ?? '...'}</b> - <a target='_blank' href="https://finder.madiator.com/leaderboard" class="filled">🔗Leaderboard</a></span>
{urlResolver !== 'madiatorFinder' && <span class="error">You need to use Madiator Finder API for scoring to work</span>}
</section>
<section>
{
route === 'profile'
? <a onClick={() => updateRoute('')} className="filled"> Back</a>
: <a className='filled' onClick={() => updateRoute('profile')} href="#profile">Profile Settings</a>
}
</section>
</header>
: <header>
{
route === 'profile'
? <a onClick={() => updateRoute('')} className="filled"> Back</a>
: <a className='filled' onClick={() => updateRoute('profile')} href="#profile">Profile Settings</a>
}
</header>
}
{
route !== ''
?
<section>
<a onClick={() => updateRoute('')} className="filled"> Back</a>
</section>
:
<section>
<a className='filled' onClick={() => updateRoute('profile')}>Profile Settings</a>
</section>
}
</header>
}
{
route === 'profile' ?
@ -82,11 +69,14 @@ function WatchOnLbryPopup(params: { profile: Awaited<ReturnType<typeof getProfil
<a onClick={() => loads(generateProfileAndSetNickname(dialogManager)).then(() => renderPopup())} className={`button active`}>
Change Nickname
</a>
<a onClick={async () =>
await dialogManager.confirm("This will delete your keypair from this device.\nStill wanna continue?\n\nNOTE: Without keypair you can't purge your data online.\nSo if you wish to purge, please use purging instead.")
&& resetProfileSettings()
&& renderPopup()
}
<a onClick={async () => {
if (!await dialogManager.confirm("This will delete your keypair from this device."
+ "\nStill wanna continue?"
+ "\n\nNOTE: Without keypair you can't purge your data online."
+ "\nSo if you wish to purge, please use purging instead.")) return
resetProfileSettings()
renderPopup()
}}
className={`button`}
>
Forget/Logout
@ -100,7 +90,7 @@ function WatchOnLbryPopup(params: { profile: Awaited<ReturnType<typeof getProfil
<a onClick={() => exportProfileKeysAsFile()} className={`button active`}>
Export
</a>
<a onClick={() => importButtonClick()}
<a onClick={() => openImportPopup()}
className={`button`}
>
Import
@ -111,7 +101,7 @@ function WatchOnLbryPopup(params: { profile: Awaited<ReturnType<typeof getProfil
<label>Purge your profile and data!</label>
<p>Purge your profile data online and offline.</p>
<div className='options'>
<div className="purge-aaaaaaa">
<div className="center">
<span className='filled'>(°° </span>
</div>
<a onClick={() => loads(purgeProfile(dialogManager)).then(() => renderPopup())} className={`button`}>
@ -139,7 +129,7 @@ function WatchOnLbryPopup(params: { profile: Awaited<ReturnType<typeof getProfil
<label>You don't have a profile.</label>
<p>You can either import keypair for an existing profile or generate a new profile keypair.</p>
<div className='options'>
<a onClick={() => importButtonClick()} className={`button`}>
<a onClick={() => openImportPopup()} className={`button`}>
Import
</a>
<a onClick={() => loads(generateProfileAndSetNickname(dialogManager)).then(() => renderPopup())} className={`button active`}>
@ -149,48 +139,88 @@ function WatchOnLbryPopup(params: { profile: Awaited<ReturnType<typeof getProfil
</section>
</main>
:
<main>
<section>
<label>Pick a mode:</label>
<div className='options'>
<a onClick={() => setExtensionSetting('redirect', true)} className={`button ${redirect ? 'active' : ''}`}>
Redirect
route === 'advanced' ?
<main>
<section>
<label>Which platform you would like to redirect to?</label>
<div className='options'>
{targetPlatforms.map(([name, value]) =>
<a onClick={() => setExtensionSetting('targetPlatform', name)} className={`button ${targetPlatform === name ? 'active' : ''}`}>
{value.displayName}
</a>
)}
</div>
</section>
<section>
<label>Which resolver API you want to use?</label>
<div className='options'>
{ytUrlResolverOptions.map(([name, value]) =>
<a onClick={() => setExtensionSetting('urlResolver', name)} className={`button ${urlResolver === name ? 'active' : ''}`}>
{value.name}
</a>
)}
</div>
<a onClick={() => loads(lbryUrlCache.clearAll().then(() => dialogManager.alert("Cleared Cache!")))} className={`button active`}>
Clear Resolver Cache
</a>
<a onClick={() => setExtensionSetting('redirect', false)} className={`button ${redirect ? '' : 'active'}`}>
Show a button
</section>
</main>
:
<main>
<section>
<label>Auto redirect when:</label>
<div className='options'>
<div class="toggle-option">
<span>Playing a video</span>
<a onClick={() => setExtensionSetting('redirectVideo', !redirectVideo)} className={`button ${redirectVideo ? 'active' : ''}`}>
{redirectVideo ? 'Active' : 'Deactive'}
</a>
</div>
<div class="toggle-option">
<span>Playing a playlist</span>
<a onClick={() => setExtensionSetting('redirectVideoPlaylist', !redirectVideoPlaylist)} className={`button ${redirectVideoPlaylist ? 'active' : ''}`}>
{redirectVideoPlaylist ? 'Active' : 'Deactive'}
</a>
</div>
<div class="toggle-option">
<span>Viewing a channel</span>
<a onClick={() => setExtensionSetting('redirectChannel', !redirectChannel)} className={`button ${redirectChannel ? 'active' : ''}`}>
{redirectChannel ? 'Active' : 'Deactive'}
</a>
</div>
</div>
</section>
<section>
<label>Show redirect button on:</label>
<div className='options'>
<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>
<label>Tools</label>
<a target='_blank' href='/pages/YTtoLBRY/index.html' className={`filled`}>
Subscription Converter
</a>
</div>
</section>
<section>
<label>Which platform you would like to redirect?</label>
<div className='options'>
{targetPlatforms.map(([name, value]) =>
<a onClick={() => setExtensionSetting('targetPlatform', name)} className={`button ${targetPlatform === name ? 'active' : ''}`}>
{value.displayName}
</a>
)}
</div>
</section>
<section>
<label>Which resolver API you want to use?</label>
<div className='options'>
{ytUrlResolverOptions.map(([name, value]) =>
<a onClick={() => setExtensionSetting('urlResolver', name)} className={`button ${urlResolver === name ? 'active' : ''}`}>
{value.name}
</a>
)}
</div>
<a onClick={() => loads(LbryPathnameCache.clearAll().then(() => dialogManager.alert("Cleared Cache!")))} className={`button active`}>
Clear Resolver Cache
</a>
</section>
<section>
<label>Tools</label>
<a target='_blank' href='/pages/YTtoLBRY/index.html' className={`filled`}>
Subscription Converter
</a>
</section>
</main>
<a className='filled' onClick={() => updateRoute('advanced')}>Advanced Settings</a>
</section>
</main>
}
{loading && <div class="overlay">
<span>Loading...</span>

View file

@ -1,3 +1,9 @@
#popup {
width: 40em;
overflow: hidden;
margin: auto;
}
header {
display: grid;
gap: .5em;
@ -21,24 +27,29 @@ section {
gap: .75em;
}
section>label {
label {
font-size: 1.75em;
font-weight: bold;
text-align: center;
}
section>.options {
padding: 0 1.5em;
section>* {
padding: 0 1rem;
}
#popup {
width: 35em;
max-width: 100%;
overflow: hidden;
margin: auto;
}
.purge-aaaaaaa {
.center {
display: grid;
justify-items: center;
}
place-items: center;
}
.left {
display: grid;
justify-items: start;
align-items: center;
text-align: left;
}
.toggle-option {
display: grid;
gap: .5em;
}

View file

@ -2,27 +2,35 @@ import { resolveById } from "../modules/yt/urlResolve"
const onGoingLbryPathnameRequest: Record<string, ReturnType<typeof resolveById>> = {}
chrome.runtime.onMessage.addListener(({ json }, sender, sendResponse) => {
chrome.runtime.onMessage.addListener(({ method, data }, sender, sendResponse) => {
function resolve(result: Awaited<ReturnType<typeof resolveById>>) {
sendResponse(JSON.stringify(result))
}
(async () => {
try {
const params: Parameters<typeof resolveById> = JSON.parse(json)
// Don't create a new Promise for same ID until on going one is over.
const promise = onGoingLbryPathnameRequest[json] ?? (onGoingLbryPathnameRequest[json] = resolveById(...params))
console.log('lbrypathname request', params, await promise)
resolve(await promise)
} catch (error) {
sendResponse('error')
console.error(error)
}
finally {
delete onGoingLbryPathnameRequest[json]
switch (method) {
case 'openTab':
{
const { href }: { href: string } = JSON.parse(data)
chrome.tabs.create({ url: href, active: sender.tab?.active, index: sender.tab ? sender.tab.index + 1 : undefined })
}
break
case 'resolveUrl':
try {
const params: Parameters<typeof resolveById> = JSON.parse(data)
// Don't create a new Promise for same ID until on going one is over.
const promise = onGoingLbryPathnameRequest[data] ?? (onGoingLbryPathnameRequest[data] = resolveById(...params))
resolve(await promise)
} catch (error) {
sendResponse(`error: ${(error as any).toString()}`)
console.error(error)
}
finally {
delete onGoingLbryPathnameRequest[data]
}
break
}
})()
return true
})
chrome.tabs.onUpdated.addListener((tabId, changeInfo) => changeInfo.status === 'complete' && chrome.tabs.sendMessage(tabId, { message: 'url-changed' }))
})

View file

@ -1,121 +1,180 @@
import { h, render } from 'preact'
import { parseYouTubeURLTimeString } from '../modules/yt'
import { resolveById } from '../modules/yt/urlResolve'
import { getExtensionSettingsAsync, getSourcePlatfromSettingsFromHostname, TargetPlatform, targetPlatformSettings } from '../settings'
import type { resolveById, ResolveUrlTypes } from '../modules/yt/urlResolve'
import { getExtensionSettingsAsync, getSourcePlatfromSettingsFromHostname, getTargetPlatfromSettingsEntiries, SourcePlatform, sourcePlatfromSettings, TargetPlatform, targetPlatformSettings } from '../settings';
const sleep = (t: number) => new Promise(resolve => setTimeout(resolve, t))
interface WatchOnLbryButtonParameters {
targetPlatform?: TargetPlatform
lbryPathname?: string
time?: number
}
interface Target {
platfrom: TargetPlatform
lbryPathname: string
time: number | null
}
function WatchOnLbryButton({ targetPlatform, lbryPathname, time }: WatchOnLbryButtonParameters) {
if (!lbryPathname || !targetPlatform) return null
const url = new URL(`${targetPlatform.domainPrefix}${lbryPathname}`)
if (time) url.searchParams.set('t', time.toFixed(0))
return <div style={{ display: 'flex', justifyContent: 'center', flexDirection: 'column' }}>
<a href={`${url.toString()}`} role='button'
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
gap: '12px',
borderRadius: '2px',
backgroundColor: targetPlatform.theme,
border: '0',
color: 'whitesmoke',
padding: '10px 16px',
marginRight: '4px',
fontSize: '14px',
textDecoration: 'none',
...targetPlatform.button.style?.button,
}}>
<img src={targetPlatform.button.icon} height={16}
style={{ transform: 'scale(1.5)', ...targetPlatform.button.style?.icon }} />
<span>{targetPlatform.button.text}</span>
</a>
</div>
}
function updateButton(mountPoint: HTMLDivElement, target: Target | null): void {
if (!target) return render(<WatchOnLbryButton />, mountPoint)
render(<WatchOnLbryButton targetPlatform={target.platfrom} lbryPathname={target.lbryPathname} time={target.time ?? undefined} />, mountPoint)
}
/** Returns a mount point for the button */
async function findButtonMountPoint(): Promise<HTMLDivElement> {
const id = 'watch-on-lbry-button-container'
let mountBefore: HTMLDivElement | null = null
const sourcePlatform = getSourcePlatfromSettingsFromHostname(new URL(location.href).hostname)
if (!sourcePlatform) throw new Error(`Unknown source of: ${location.href}`)
const exits: HTMLDivElement | null = document.querySelector(`#${id}`)
if (exits) return exits
while (!(mountBefore = document.querySelector(sourcePlatform.htmlQueries.mountButtonBefore))) await sleep(200)
const div = document.createElement('div')
div.id = id
div.style.display = 'flex'
div.style.alignItems = 'center'
mountBefore.parentElement?.insertBefore(div, mountBefore)
return div
}
async function findVideoElement() {
const sourcePlatform = getSourcePlatfromSettingsFromHostname(new URL(location.href).hostname)
if (!sourcePlatform) throw new Error(`Unknown source of: ${location.href}`)
let videoElement: HTMLVideoElement | null = null
while (!(videoElement = document.querySelector(sourcePlatform.htmlQueries.videoPlayer))) await sleep(200)
return videoElement
}
// 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') throw new Error("Background error.")
return json ? JSON.parse(json) : null
}
// Start
(async () => {
const settings = await getExtensionSettingsAsync()
let updater: (() => Promise<void>)
const sleep = (t: number) => new Promise(resolve => setTimeout(resolve, t))
interface Target {
platform: TargetPlatform
lbryPathname: string
type: ResolveUrlTypes
time: number | null
}
interface Source {
platform: SourcePlatform
id: string
type: ResolveUrlTypes
url: URL
time: number | null
}
const targetPlatforms = getTargetPlatfromSettingsEntiries()
const settings = await getExtensionSettingsAsync()
// Listen Settings Change
chrome.storage.onChanged.addListener(async (changes, areaName) => {
if (areaName !== 'local') return
Object.assign(settings, Object.fromEntries(Object.entries(changes).map(([key, change]) => [key, change.newValue])))
if (changes.redirect) await onModeChange()
await updater()
})
/*
* Gets messages from background script which relays tab update events. This is because there's no sensible way to detect
* history.pushState changes from a content script
*/
// Listen URL Change
chrome.runtime.onMessage.addListener(({ message }, sender) => message === 'url-changed' && updater())
const buttonMountPoint = document.createElement('div')
buttonMountPoint.style.display = 'inline-flex'
const playerButtonMountPoint = document.createElement('div')
playerButtonMountPoint.style.display = 'inline-flex'
function WatchOnLbryButton({ source, target }: { source?: Source, target?: Target }) {
if (!target || !source) return null
const url = getLbryUrlByTarget(target)
return <div
style={{
display: 'grid',
gridTemplateRows: '36px',
gridAutoColumns: 'auto',
alignContent: 'center'
}}
>
<a href={`${url.href}`} target={target.platform === targetPlatformSettings.app ? '' : '_blank'} role='button'
style={{
display: 'flex',
alignItems: 'center',
gap: '7px',
borderRadius: '2px',
padding: '0 16px',
margin: '0 4px',
fontWeight: 'bold',
border: '0',
color: 'whitesmoke',
fontSize: '14px',
textDecoration: 'none',
backgroundColor: target.platform.theme,
backgroundImage: target.platform.theme,
...target.platform.button.style?.button,
}}
onClick={() => findVideoElementAwait(source).then((videoElement) => {
videoElement.pause()
})}
>
<img src={target.platform.button.icon} height={24} style={{ ...target.platform.button.style?.icon }} />
<span>{target.type === 'channel' ? 'Channel on' : 'Watch on'} {target.platform.button.platformNameText}</span>
</a>
</div>
}
function WatchOnLbryPlayerButton({ source, target }: { source?: Source, target?: Target }) {
if (!target || !source) return null
const url = getLbryUrlByTarget(target)
return <div
style={{
display: 'grid',
gridTemplateRows: '36px',
gridAutoColumns: 'auto',
alignContent: 'center'
}}
>
<a href={`${url.href}`} target={target.platform === targetPlatformSettings.app ? '' : '_blank'} role='button'
style={{
display: 'flex',
alignItems: 'center',
gap: '7px',
borderRadius: '2px',
paddingRight: '10px',
fontWeight: 'bold',
border: '0',
color: 'whitesmoke',
fontSize: '14px',
textDecoration: 'none',
...target.platform.button.style?.button,
}}
onClick={() => findVideoElementAwait(source).then((videoElement) => {
videoElement.pause()
})}
>
<img src={target.platform.button.icon} height={24} style={{ ...target.platform.button.style?.icon }} />
<span>{target.type === 'channel' ? 'Channel on' : 'Watch on'} {target.platform.button.platformNameText}</span>
</a>
</div>
}
function updateButtons(params: { source: Source, target: Target } | null): void {
if (!params) {
render(<WatchOnLbryButton />, buttonMountPoint)
render(<WatchOnLbryPlayerButton />, playerButtonMountPoint)
return
}
{
const mountPlayerButtonBefore = settings.buttonVideoPlayer ?
document.querySelector(params.source.platform.htmlQueries.mountPoints.mountPlayerButtonBefore) :
null
if (!mountPlayerButtonBefore) render(<WatchOnLbryPlayerButton />, playerButtonMountPoint)
else {
if (playerButtonMountPoint.getAttribute('data-id') !== params.source.id) {
mountPlayerButtonBefore.parentElement?.insertBefore(playerButtonMountPoint, mountPlayerButtonBefore)
playerButtonMountPoint.setAttribute('data-id', params.source.id)
}
render(<WatchOnLbryPlayerButton target={params.target} source={params.source} />, playerButtonMountPoint)
}
}
{
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]) :
null
if (!mountButtonBefore) render(<WatchOnLbryButton />, buttonMountPoint)
else {
if (buttonMountPoint.getAttribute('data-id') !== params.source.id) {
mountButtonBefore.parentElement?.insertBefore(buttonMountPoint, mountButtonBefore)
buttonMountPoint.setAttribute('data-id', params.source.id)
}
render(<WatchOnLbryButton target={params.target} source={params.source} />, buttonMountPoint)
}
}
}
async function findVideoElementAwait(source: Source) {
let videoElement: HTMLVideoElement | null = null
while (!(videoElement = document.querySelector(source.platform.htmlQueries.videoPlayer))) await sleep(200)
return videoElement
}
async function getSourceByUrl(url: URL): Promise<Source | null> {
const platform = getSourcePlatfromSettingsFromHostname(new URL(location.href).hostname)
if (!platform) return null
async function getTargetByURL(url: URL) {
if (url.pathname === '/watch' && url.searchParams.has('v')) {
const videoId = url.searchParams.get('v')!
const result = await requestResolveById([{ id: videoId, type: 'video' }])
const target: Target | null = result?.[videoId] ? { lbryPathname: result[videoId].id, platfrom: targetPlatformSettings[settings.targetPlatform], time: null } : null
return target
return {
id: url.searchParams.get('v')!,
platform,
time: url.searchParams.has('t') ? parseYouTubeURLTimeString(url.searchParams.get('t')!) : null,
type: 'video',
url
}
}
else if (url.pathname.startsWith('/channel/')) {
await requestResolveById([{ id: url.pathname.substring("/channel/".length), type: 'channel' }])
return {
id: url.pathname.substring("/channel/".length),
platform,
time: null,
type: 'channel',
url
}
}
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
@ -125,72 +184,180 @@ async function requestResolveById(...params: Parameters<typeof resolveById>): Re
const suffix = `"`
const startsAt = content.indexOf(prefix) + prefix.length
const endsAt = content.indexOf(suffix, startsAt)
await requestResolveById([{ id: content.substring(startsAt, endsAt), type: 'channel' }])
const id = content.substring(startsAt, endsAt)
return {
id,
platform,
time: null,
type: 'channel',
url
}
}
return null
}
async function redirectTo({ lbryPathname, platfrom, time }: Target) {
const url = new URL(`${platfrom.domainPrefix}${lbryPathname}`)
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]
if (time) url.searchParams.set('t', time.toFixed(0))
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
]
findVideoElement().then((videoElement) => {
videoElement.addEventListener('play', () => videoElement.pause(), { once: true })
videoElement.pause()
})
return [
source.id,
{
type: result.type,
lbryPathname: result.id,
platform,
time: source.time
}
]
})
)
if (platfrom === targetPlatformSettings.app) {
if (document.hidden) await new Promise((resolve) => document.addEventListener('visibilitychange', resolve, { once: true }))
// On redirect with app, people might choose to cancel browser's dialog
// So we dont destroy the current window automatically for them
// And also we are keeping the same window for less distiraction
if (settings.redirect) {
location.replace(url.toString())
}
else {
open(url.toString(), '_blank')
if (window.history.length === 1) window.close()
else window.history.back()
}
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 response = await new Promise<string | null | 'error'>((resolve) => chrome.runtime.sendMessage({ method: 'resolveUrl', data: JSON.stringify(params) }, resolve))
if (response?.startsWith('error:')) {
console.error("Background error on:", params)
throw new Error(`Background error. ${response ?? ''}`)
}
else
location.replace(url.toString())
return response ? JSON.parse(response) : null
}
let removeVideoTimeUpdateListener: (() => void) | null = null
async function onModeChange() {
let target: Target | null = null
if (settings.redirect)
updater = async () => {
const url = new URL(location.href)
target = await getTargetByURL(url)
if (!target) return
target.time = url.searchParams.has('t') ? parseYouTubeURLTimeString(url.searchParams.get('t')!) : null
redirectTo(target)
}
else {
const mountPoint = await findButtonMountPoint()
const videoElement = await findVideoElement()
const getTime = () => videoElement.currentTime > 3 && videoElement.currentTime < videoElement.duration - 1 ? videoElement.currentTime : null
const onTimeUpdate = () => target && updateButton(mountPoint, Object.assign(target, { time: getTime() }))
removeVideoTimeUpdateListener?.call(null)
videoElement.addEventListener('timeupdate', onTimeUpdate)
removeVideoTimeUpdateListener = () => videoElement.removeEventListener('timeupdate', onTimeUpdate)
updater = async () => {
const url = new URL(location.href)
target = await getTargetByURL(url)
if (target) target.time = getTime()
updateButton(mountPoint, target)
}
}
await updater()
// Request new tab
async function openNewTab(url: URL) {
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) {
const url = new URL(`${target.platform.domainPrefix}${target.lbryPathname}`)
if (target.time) url.searchParams.set('t', target.time.toFixed(0))
return url
}
// Master Loop
for (
let url = new URL(location.href),
urlHrefCache: string | null = null;
;
urlHrefCache = url.href,
url = new URL(location.href)
) {
await sleep(500)
try {
const source = await getSourceByUrl(new URL(location.href))
if (!source) {
updateButtons(null)
continue
}
const target = (await getTargetsBySources(source))[source.id] ?? findTargetFromSourcePage(source)
if (!target) {
updateButtons(null)
continue
}
// 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())
}
if (target.platform === targetPlatformSettings.app) {
if (document.hidden) await new Promise((resolve) => document.addEventListener('visibilitychange', resolve, { once: true }))
// 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 {
openNewTab(lbryURL)
if (window.history.length === 1)
window.close()
else
window.history.back()
}
}
} catch (error) {
console.error(error)
}
}
await onModeChange()
})()

View file

@ -0,0 +1,2 @@
import './settings/background'
import './scripts/background'

View file

@ -1,31 +1,33 @@
import { DEFAULT_SETTINGS, ExtensionSettings, getExtensionSettingsAsync, setExtensionSetting, targetPlatformSettings, ytUrlResolversSettings } from '.'
import { DEFAULT_SETTINGS, ExtensionSettings, getExtensionSettingsAsync, setExtensionSetting, targetPlatformSettings, ytUrlResolversSettings } from '../settings'
// This is for manifest v2 and v3
const chromeAction = chrome.action ?? chrome.browserAction
/** Reset settings to default value and update the browser badge text */
async function initSettings() {
let settings = await getExtensionSettingsAsync()
let settings = await getExtensionSettingsAsync()
// get all the values that aren't set and use them as a change set
const invalidEntries = (Object.entries(DEFAULT_SETTINGS) as Array<[keyof ExtensionSettings, ExtensionSettings[keyof ExtensionSettings]]>)
.filter(([k]) => settings[k] === undefined || settings[k] === null)
// get all the values that aren't set and use them as a change set
const invalidEntries = (Object.entries(DEFAULT_SETTINGS) as Array<[keyof ExtensionSettings, ExtensionSettings[keyof ExtensionSettings]]>)
.filter(([k]) => settings[k] === undefined || settings[k] === null)
// fix our local var and set it in storage for later
if (invalidEntries.length > 0) {
const changeSet = Object.fromEntries(invalidEntries)
chrome.storage.local.set(changeSet)
settings = await getExtensionSettingsAsync()
}
// fix our local var and set it in storage for later
if (invalidEntries.length > 0) {
const changeSet = Object.fromEntries(invalidEntries)
chrome.storage.local.set(changeSet)
settings = await getExtensionSettingsAsync()
}
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(targetPlatformSettings).includes(settings.targetPlatform)) setExtensionSetting('targetPlatform', DEFAULT_SETTINGS.targetPlatform)
if (!Object.keys(ytUrlResolversSettings).includes(settings.urlResolver)) setExtensionSetting('urlResolver', DEFAULT_SETTINGS.urlResolver)
chrome.browserAction.setBadgeText({ text: settings.redirect ? 'ON' : 'OFF' })
// chromeAction.setBadgeText({ text: settings.redirect ? 'ON' : 'OFF' })
}
chrome.storage.onChanged.addListener((changes, areaName) => {
if (areaName !== 'local' || !changes.redirect) return
chrome.browserAction.setBadgeText({ text: changes.redirect.newValue ? 'ON' : 'OFF' })
})
/* chrome.storage.onChanged.addListener((changes, areaName) => {
if (areaName !== 'local' || !changes.redirect) return
chromeAction.setBadgeText({ text: changes.redirect.newValue ? 'ON' : 'OFF' })
}) */
chrome.runtime.onStartup.addListener(initSettings)
chrome.runtime.onInstalled.addListener(initSettings)
chrome.runtime.onInstalled.addListener(initSettings)

View file

@ -1,18 +1,29 @@
import { JSX } from "preact"
import type { JSX } from "preact"
import { useEffect, useReducer } from "preact/hooks"
import type { ResolveUrlTypes } from "../modules/yt/urlResolve"
export interface ExtensionSettings {
redirect: boolean
export interface ExtensionSettings extends Record<string, string | number | boolean | null | undefined>{
targetPlatform: TargetPlatformName
urlResolver: YTUrlResolverName
urlResolver: YTUrlResolverName,
redirectVideo: boolean,
redirectChannel: boolean,
redirectVideoPlaylist: boolean,
buttonVideoSub: boolean
buttonVideoPlayer: boolean
buttonChannelSub: boolean
publicKey: string | null,
privateKey: string | null
}
export const DEFAULT_SETTINGS: ExtensionSettings = {
redirect: true,
targetPlatform: 'odysee',
urlResolver: 'odyseeApi',
redirectVideo: false,
redirectChannel: false,
redirectVideoPlaylist: false,
buttonVideoSub: true,
buttonVideoPlayer: true,
buttonChannelSub: true,
privateKey: null,
publicKey: null
}
@ -59,7 +70,7 @@ const targetPlatform = (o: {
displayName: string
theme: string
button: {
text: string
platformNameText: string,
icon: string
style?:
{
@ -77,31 +88,31 @@ export const targetPlatformSettings = {
'madiator.com': targetPlatform({
domainPrefix: 'https://madiator.com/',
displayName: 'Madiator.com',
theme: '#075656',
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' },
icon: { transform: 'scale(1.2)' }
icon: { }
}
}
}),
odysee: targetPlatform({
domainPrefix: 'https://odysee.com/',
displayName: 'Odysee',
theme: '#1e013b',
theme: 'linear-gradient(130deg, #c63d59, #f77937)',
button: {
text: 'Watch on Odysee',
platformNameText: 'Odysee',
icon: chrome.runtime.getURL('assets/icons/lbry/odysee-logo.svg')
}
}),
app: targetPlatform({
domainPrefix: 'lbry://',
displayName: 'LBRY App',
theme: '#075656',
theme: 'linear-gradient(130deg, #499375, #43889d)',
button: {
text: 'Watch on LBRY',
platformNameText: 'LBRY',
icon: chrome.runtime.getURL('assets/icons/lbry/lbry-logo.svg')
}
}),
@ -112,8 +123,13 @@ export const targetPlatformSettings = {
const sourcePlatform = (o: {
hostnames: string[]
htmlQueries: {
mountButtonBefore: string,
videoPlayer: string
mountPoints: {
mountButtonBefore: Record<ResolveUrlTypes, string>,
mountPlayerButtonBefore: string,
}
videoPlayer: string,
videoDescription: string
channelLinks: string
}
}) => o
export type SourcePlatform = ReturnType<typeof sourcePlatform>
@ -125,18 +141,35 @@ export function getSourcePlatfromSettingsFromHostname(hostname: string) {
return null
}
export const sourcePlatfromSettings = {
"yewtu.be": sourcePlatform({
hostnames: ['yewtu.be', 'vid.puffyan.us', 'invidio.xamh.de', 'invidious.kavin.rocks'],
htmlQueries: {
mountButtonBefore: '#watch-on-youtube',
videoPlayer: '#player-container video'
}
}),
"youtube.com": sourcePlatform({
hostnames: ['www.youtube.com'],
htmlQueries: {
mountButtonBefore: 'ytd-video-owner-renderer~#subscribe-button',
videoPlayer: '#ytd-player video'
mountPoints: {
mountButtonBefore: {
video: 'ytd-video-owner-renderer~#subscribe-button',
channel: '#channel-header-container #buttons #subscribe-button'
},
mountPlayerButtonBefore: 'ytd-watch-flexy ytd-player .ytp-right-controls',
},
videoPlayer: '#ytd-player video',
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: {
mountPoints: {
mountButtonBefore:
{
video: '#subscribe',
channel: '#subscribe'
},
mountPlayerButtonBefore: '#player-container ~ .h-box > h1 > a',
},
videoPlayer: '#player-container video',
videoDescription: '#descriptionWrapper',
channelLinks: '#descriptionWrapper'
}
})
}

View file

@ -41,6 +41,7 @@
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
"importsNotUsedAsValues": "error", /* Import types always with `import type` */
/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
@ -53,7 +54,6 @@
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */