Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

youtube video battery #3198

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/app/screens/Home/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ const Home: FC = () => {

if (currentUrl.startsWith("http")) {
browser.tabs.sendMessage(tabs[0].id as number, {
action: "extractLightningData",
action: "getCurrentLightningData",
});
}
} else {
Expand Down
102 changes: 89 additions & 13 deletions src/extension/content-script/batteries/YouTubeVideo.ts
Original file line number Diff line number Diff line change
@@ -1,36 +1,65 @@
import getOriginData from "../originData";
import { findLnurlFromYouTubeAboutPage } from "./YouTubeChannel";
import { findLightningAddressInText, setLightningData } from "./helpers";
import {
findLightningAddressInText,
resetLightningData,
setLightningData,
} from "./helpers";

declare global {
interface Window {
ALBY_BATTERY: boolean;
}
}

const urlMatcher = /^https:\/\/www\.youtube.com\/watch.*/;

const battery = async (): Promise<void> => {
let oldVideoId: string;
let observer: MutationObserver | null = null;

const setData = async (): Promise<void> => {
const searchParams = new URLSearchParams(window.location.search);
const videoId = searchParams.get("v");

// to keep the battery info stable after the description settles
// youtube returns old lightning data even when switching on new video for few initial seconds. so we just return from here instead of showing old lightning data
if (videoId === oldVideoId) {
return;
}

oldVideoId = videoId as string;

let text = "";
document
.querySelectorAll(
"#columns #primary #primary-inner #meta-contents #description .content"
"ytd-watch-metadata #above-the-fold #bottom-row #description #description-inner #description-inline-expander yt-attributed-string .yt-core-attributed-string"
)
.forEach((e) => {
text += ` ${e.textContent}`;
text += `${e.textContent} `;
});

const channelLink = document.querySelector<HTMLAnchorElement>(
"#columns #primary #primary-inner #meta-contents .ytd-channel-name a"
"ytd-watch-metadata #above-the-fold #top-row #owner #upload-info .ytd-channel-name yt-formatted-string a"
);
if (!text || !channelLink) {

if (!channelLink) {
resetLightningData();
return;
}

let match;
let lnurl;
// check for an lnurl

// Check for an lnurl
if ((match = text.match(/(lnurlp:)(\S+)/i))) {
lnurl = match[2];
}
// if there is no lnurl we check for a zap emoji with a lightning address
// we check for the @-sign to try to limit the possibility to match some invalid text (e.g. random emoji usage)
// If no lnurl, check for a zap emoji with a lightning address
else if ((match = findLightningAddressInText(text))) {
lnurl = match;
} else {
// load the about page to check for a lightning address
}
// Load the about page to check for a lightning address
else {
const match = channelLink.href.match(
/^https:\/\/www\.youtube.com\/(((channel|c)\/([^/]+))|(@[^/]+)).*/
);
Expand All @@ -39,7 +68,10 @@ const battery = async (): Promise<void> => {
}
}

if (!lnurl) return;
if (!lnurl) {
resetLightningData();
return;
}

const name = channelLink.textContent || "";
const imageUrl =
Expand All @@ -50,18 +82,62 @@ const battery = async (): Promise<void> => {
"#columns #primary #primary-inner #owner #avatar img" // support maybe new UI being rolled out 2022/09
)?.src ||
"";

setLightningData([
{
method: "lnurl",
address: lnurl,
...getOriginData(),
name,
description: "", // we can not reliably find a description (the meta tag might be of a different video)
description: "", // We cannot reliably find a description (the meta tag might be of a different video)
icon: imageUrl,
},
]);
};

const battery = (): void => {
function waitForChannelLinkAndDescription() {
const description = document.querySelector(
"ytd-watch-metadata #above-the-fold #bottom-row #description #description-inner #description-inline-expander yt-attributed-string .yt-core-attributed-string"
);

const channelLink = document.querySelector<HTMLAnchorElement>(
"ytd-watch-metadata #above-the-fold #top-row #owner #upload-info .ytd-channel-name yt-formatted-string a"
);

// Ensure all elements are present before proceeding
if (description && channelLink) {
clearInterval(descriptionInterval); // Stop checking for the elements

// run this only once, during the first load
if (!window.ALBY_BATTERY) {
window.ALBY_BATTERY = true;

// we need to run setData if this is the first time the user is
// visiting youtube as the observer doesn't run intially on attach
setData();

// Re-initialize the observer
observer = new MutationObserver(() => {
setData();
});

// Observe changes in the description (without subtree it didn't work properly)
observer.observe(description, { childList: true, subtree: true });
// Observe changes in the channelLink
observer.observe(channelLink, { childList: true, subtree: true });
}
}
}

// Wait for the channel link and description to load before initializing the observer and fetching the data
const descriptionInterval = setInterval(
waitForChannelLinkAndDescription,
100
);
setTimeout(() => clearInterval(descriptionInterval), 2000);
};

const YouTubeVideo = {
urlMatcher,
battery,
Expand Down
23 changes: 18 additions & 5 deletions src/extension/content-script/batteries/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,11 +48,24 @@ export const findLightningAddressInText = (text: string): string | null => {
return null;
};

let lightningData: [Battery] | null;

export const resetLightningData = (): void => {
lightningData = null;
msg.request("setIcon", { icon: ExtensionIcon.Default });
};

export const sendLightningData = () => {
if (lightningData) {
browser.runtime.sendMessage({
application: "LBE",
action: "lightningData",
args: lightningData,
});
}
};

export const setLightningData = (data: [Battery]): void => {
browser.runtime.sendMessage({
application: "LBE",
action: "lightningData",
args: data,
});
lightningData = data;
msg.request("setIcon", { icon: ExtensionIcon.Tipping });
};
5 changes: 5 additions & 0 deletions src/extension/content-script/webln.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import browser from "webextension-polyfill";

import extractLightningData from "./batteries";
import { sendLightningData } from "./batteries/helpers";
import getOriginData from "./originData";
import shouldInject from "./shouldInject";

Expand Down Expand Up @@ -46,6 +47,10 @@ async function init() {
window.location.origin
);
}
// homepage requests this to get current lightning data from battery
if (request.action === "getCurrentLightningData") {
sendLightningData();
}
});

// message listener to listen to inpage webln/webbtc calls
Expand Down
Loading