Advanced stats for patreon supporters (#1222)

* auth works

* Works after review.

* switched to auth flow

* all works well in chrome

* all works well in chrome and firefox

* translations harmonized

* translations harmonized

* website translations

* Translations harmonized.

* Everything kinda works

* Almost works

* all works

* all works

* all works #2

* Streamline premium analytics range handling

* Restore premium analytics selection flow

* Fix analytics zoom interactions

* Add per-section expansion controls to premium analytics

* Adjust map legend visibility for premium analytics

* Add missing country synonyms for premium map

* Remove legacy premium badge overlay

* Polish premium analytics controls for light theme

* Refresh map legend when toggling sections

* Improve light-mode styling for range selectors

* Fix map mode switching regression

* Fix for panel expand

* Typo fix

* webpack fix

* before next steps.

* split, zero-buckets

* bucket size indicated on UI

* all works

* first/last toggle

* breadcrumbs

* release
This commit is contained in:
Dmitrii Selivanov authored and GitHub committed 2025-10-20 18:43:06 +02:00
1 parent fb46b07db6
commit 40fda6dd32
174 files changed
+20235 -2619

No files matched your search

+290 -34
View File
@@ -1,24 +1,108 @@
const apiUrl = "https://returnyoutubedislikeapi.com";
const voteDisabledIconName = "icon_hold128.png";
const defaultIconName = "icon128.png";
import { config, getApiUrl, getApiEndpoint, getChangelogUrl } from "./src/config";
const apiUrl = getApiUrl();
const voteDisabledIconName = config.voteDisabledIconName;
const defaultIconName = config.defaultIconName;
let api;
const CHANGELOG_STORAGE_KEY = "lastShownChangelogVersion";
/** stores extension's global config */
let extConfig = {
disableVoteSubmission: false,
disableLogging: true,
coloredThumbs: false,
coloredBar: false,
colorTheme: "classic", // classic, accessible, neon
numberDisplayFormat: "compactShort", // compactShort, compactLong, standard
numberDisplayReformatLikes: false, // use existing (native) likes number
};
let extConfig = { ...config.defaultExtConfig };
if (isChrome()) api = chrome;
else if (isFirefox()) api = browser;
initExtConfig();
function broadcastPatreonStatus(authenticated, user, sessionToken) {
chrome.tabs.query({}, (tabs) => {
tabs
.filter((tab) => tab.url && tab.url.includes("youtube.com"))
.forEach((tab) => {
const maybePromise = chrome.tabs.sendMessage(
tab.id,
{
message: "patreon_status_changed",
authenticated,
user: authenticated ? user : null,
sessionToken: authenticated ? sessionToken : null,
},
() => {
if (chrome.runtime.lastError) {
console.debug("Patreon status broadcast skipped:", chrome.runtime.lastError.message);
}
},
);
if (maybePromise && typeof maybePromise.catch === "function") {
maybePromise.catch((error) => {
console.debug("Patreon status broadcast skipped:", error?.message ?? error);
});
}
});
});
}
function handlePatreonAuthComplete(user, sessionToken, done) {
if (!user) {
done?.();
return;
}
chrome.storage.sync.set(
{
patreonAuthenticated: true,
patreonUser: user,
patreonSessionToken: sessionToken,
},
() => {
broadcastPatreonStatus(true, user, sessionToken);
done?.();
},
);
}
function getIdentityApi() {
if (isFirefox() && browser.identity) return browser.identity;
if (isChrome() && chrome.identity) return chrome.identity;
return null;
}
function launchWebAuthFlow(url) {
try {
if (isFirefox() && browser.identity && typeof browser.identity.launchWebAuthFlow === "function") {
return browser.identity.launchWebAuthFlow({ url, interactive: true });
}
} catch (_) {}
return new Promise((resolve, reject) => {
if (!isChrome() || !chrome.identity || typeof chrome.identity.launchWebAuthFlow !== "function") {
reject(new Error("identity API not available"));
return;
}
chrome.identity.launchWebAuthFlow({ url, interactive: true }, (responseUrl) => {
const err = chrome.runtime && chrome.runtime.lastError;
if (err) reject(err);
else resolve(responseUrl);
});
});
}
function extractOAuthParams(responseUrl) {
try {
const u = new URL(responseUrl);
let code = u.searchParams.get("code");
let state = u.searchParams.get("state");
if (!code && u.hash) {
const hashParams = new URLSearchParams(u.hash.startsWith("#") ? u.hash.substring(1) : u.hash);
code = hashParams.get("code");
state = state || hashParams.get("state");
}
return { code, state };
} catch (_) {
return { code: null, state: null };
}
}
api.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.message === "get_auth_token") {
chrome.identity.getAuthToken({ interactive: true }, function (token) {
@@ -29,10 +113,40 @@ api.runtime.onMessage.addListener((request, sender, sendResponse) => {
});
} else if (request.message === "log_off") {
// chrome.identity.clearAllCachedAuthTokens(() => console.log("logged off"));
} else if (request.message === "patreon_auth_complete") {
handlePatreonAuthComplete(request.user, request.sessionToken);
} else if (request.message === "patreon_logout") {
// Clear Patreon authentication
chrome.storage.sync.remove(["patreonAuthenticated", "patreonUser", "patreonSessionToken"], () => {
broadcastPatreonStatus(false, null, null);
});
} else if (request.message === "ryd_open_tab") {
const targetUrl = typeof request?.url === "string" ? request.url : null;
if (!targetUrl) {
sendResponse?.({ success: false, error: "invalid_url" });
return;
}
try {
if (api?.tabs?.create) {
api.tabs.create({ url: targetUrl }, () => {
if (api.runtime?.lastError) {
console.debug("Tab open failed:", api.runtime.lastError.message);
}
});
sendResponse?.({ success: true });
return;
}
} catch (error) {
console.debug("Tab open threw:", error?.message ?? error);
}
sendResponse?.({ success: false, error: "tabs_api_unavailable" });
return;
} else if (request.message == "set_state") {
// chrome.identity.getAuthToken({ interactive: true }, function (token) {
let token = "";
fetch(`${apiUrl}/votes?videoId=${request.videoId}&likeCount=${request.likeCount || ""}`, {
fetch(getApiEndpoint(`/votes?videoId=${request.videoId}&likeCount=${request.likeCount || ""}`), {
method: "GET",
headers: {
Accept: "application/json",
@@ -47,7 +161,7 @@ api.runtime.onMessage.addListener((request, sender, sendResponse) => {
} else if (request.message == "send_links") {
toSend = toSend.concat(request.videoIds.filter((x) => !sentIds.has(x)));
if (toSend.length >= 20) {
fetch(`${apiUrl}/votes`, {
fetch(getApiEndpoint("/votes"), {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -65,24 +179,146 @@ api.runtime.onMessage.addListener((request, sender, sendResponse) => {
} else if (request.message == "send_vote") {
sendVote(request.videoId, request.vote);
return true;
} else if (request.message === "patreon_oauth_login") {
(async () => {
try {
const idApi = getIdentityApi();
if (
!idApi ||
typeof (idApi.getRedirectURL || (isChrome() && chrome.identity && chrome.identity.getRedirectURL)) !==
"function"
) {
sendResponse({ success: false, error: "identity API not available" });
return;
}
const redirectUri =
isFirefox() && browser.identity.getRedirectURL
? browser.identity.getRedirectURL()
: isChrome() && chrome.identity.getRedirectURL
? chrome.identity.getRedirectURL()
: "";
const startRes = await fetch(
getApiEndpoint(`/api/auth/oauth/login?redirectUri=${encodeURIComponent(redirectUri)}`),
);
const startData = await startRes.json();
const responseUrl = await launchWebAuthFlow(startData.authUrl);
const { code, state } = extractOAuthParams(responseUrl);
if (!code) {
sendResponse({ success: false, error: "No authorization code received" });
return;
}
const exchangeRes = await fetch(getApiEndpoint("/api/auth/oauth/exchange"), {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
code,
state,
expectedState: startData.state,
redirectUri: startData.redirectUri || redirectUri,
}),
});
const authData = await exchangeRes.json();
if (authData && authData.success) {
handlePatreonAuthComplete(authData.user, authData.sessionToken, () => {
sendResponse({ success: true, user: authData.user });
});
} else {
sendResponse({ success: false, error: (authData && authData.error) || "OAuth exchange failed" });
}
} catch (e) {
console.error("patreon_oauth_login error", e);
sendResponse({ success: false, error: String((e && e.message) || e) });
}
})();
return true;
}
});
api.runtime.onInstalled.addListener((details) => {
if (
// No need to show changelog if its was a browser update (and not extension update)
details.reason === "browser_update" ||
// Chromium (e.g., Google Chrome Cannary) uses this name instead of the one above for some reason
details.reason === "chrome_update" ||
// No need to show changelog if developer just reloaded the extension
details.reason === "update"
) {
return;
} else if (details.reason == "install") {
api.tabs.create({
url: api.runtime.getURL("/changelog/3/changelog_3.0.html"),
function openChangelogTab(version) {
try {
const url = getChangelogUrl();
api.tabs.create({ url }, () => {
if (api.runtime.lastError) {
console.debug("Changelog tab could not open:", api.runtime.lastError.message);
}
persistChangelogVersion(version);
});
} catch (error) {
console.debug("Failed to open changelog tab", error);
}
}
function persistChangelogVersion(version) {
const storage = api?.storage?.local;
if (!storage || typeof storage.set !== "function") {
return;
}
try {
storage.set({ [CHANGELOG_STORAGE_KEY]: version }, () => {
if (api.runtime.lastError) {
console.debug("Failed to persist changelog version:", api.runtime.lastError.message);
}
});
} catch (error) {
console.debug("Storage set failed for changelog version", error);
}
}
function maybeShowChangelog(details) {
const reason = details?.reason;
if (!reason) {
return;
}
if (reason === "browser_update" || reason === "chrome_update") {
return;
}
const manifest = api.runtime.getManifest();
const currentVersion = manifest?.version;
if (!currentVersion) {
return;
}
const storage = api?.storage?.local;
if (reason === "install") {
openChangelogTab(currentVersion);
return;
}
if (reason === "update") {
if (!storage || typeof storage.get !== "function") {
openChangelogTab(currentVersion);
return;
}
try {
storage.get(CHANGELOG_STORAGE_KEY, (result) => {
if (api.runtime.lastError) {
console.debug("Changelog storage read failed:", api.runtime.lastError.message);
openChangelogTab(currentVersion);
return;
}
const lastShownVersion = result?.[CHANGELOG_STORAGE_KEY];
if (lastShownVersion === currentVersion) {
return;
}
openChangelogTab(currentVersion);
});
} catch (error) {
console.debug("Storage get failed for changelog version", error);
openChangelogTab(currentVersion);
}
}
}
api.runtime.onInstalled.addListener((details) => {
maybeShowChangelog(details);
});
// api.storage.sync.get(['lastShowChangelogVersion'], (details) => {
@@ -92,7 +328,7 @@ api.runtime.onInstalled.addListener((details) => {
// // keep it inside get to avoid race condition
// api.storage.sync.set({'lastShowChangelogVersion ': chrome.runtime.getManifest().version});
// // wait until async get runs & don't steal tab focus
// api.tabs.create({url: api.runtime.getURL("/changelog/3/changelog_3.0.html"), active: false});
// api.tabs.create({url: api.runtime.getURL("/changelog/4/changelog_4.0.html"), active: false});
// }
// });
@@ -101,7 +337,7 @@ async function sendVote(videoId, vote, depth = 1) {
if (!storageResult.userId || !storageResult.registrationConfirmed) {
await register();
}
let voteResponse = await fetch(`${apiUrl}/interact/vote`, {
let voteResponse = await fetch(getApiEndpoint("/interact/vote"), {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -115,9 +351,10 @@ async function sendVote(videoId, vote, depth = 1) {
if (voteResponse.status == 401 && depth > 0) {
await register();
await sendVote(videoId, vote, depth-1);
await sendVote(videoId, vote, depth - 1);
return;
} else if (voteResponse.status == 401) { // We have already tried registering
} else if (voteResponse.status == 401) {
// We have already tried registering
return;
}
@@ -128,7 +365,7 @@ async function sendVote(videoId, vote, depth = 1) {
return;
}
await fetch(`${apiUrl}/interact/confirmVote`, {
await fetch(getApiEndpoint("/interact/confirmVote"), {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -145,7 +382,7 @@ async function sendVote(videoId, vote, depth = 1) {
async function register() {
const userId = generateUserID();
api.storage.sync.set({ userId });
const registrationResponse = await fetch(`${apiUrl}/puzzle/registration?userId=${userId}`, {
const registrationResponse = await fetch(getApiEndpoint(`/puzzle/registration?userId=${userId}`), {
method: "GET",
headers: {
Accept: "application/json",
@@ -156,7 +393,7 @@ async function register() {
await register();
return;
}
const result = await fetch(`${apiUrl}/puzzle/registration?userId=${userId}`, {
const result = await fetch(getApiEndpoint(`/puzzle/registration?userId=${userId}`), {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -273,6 +510,9 @@ function storageChangeHandler(changes, area) {
if (changes.numberDisplayReformatLikes !== undefined) {
handleNumberDisplayReformatLikesChangeEvent(changes.numberDisplayReformatLikes.newValue);
}
if (changes.hidePremiumTeaser !== undefined) {
handleHidePremiumTeaserChangeEvent(changes.hidePremiumTeaser.newValue);
}
}
function handleDisableVoteSubmissionChangeEvent(value) {
@@ -328,6 +568,10 @@ function handleNumberDisplayReformatLikesChangeEvent(value) {
extConfig.numberDisplayReformatLikes = value;
}
function handleHidePremiumTeaserChangeEvent(value) {
extConfig.hidePremiumTeaser = value === true;
}
api.storage.onChanged.addListener(storageChangeHandler);
function initExtConfig() {
@@ -340,6 +584,7 @@ function initExtConfig() {
initializeNumberDisplayReformatLikes();
initializeTooltipPercentage();
initializeTooltipPercentageMode();
initializeHidePremiumTeaser();
}
function initializeDisableVoteSubmission() {
@@ -433,6 +678,17 @@ function initializeNumberDisplayReformatLikes() {
});
}
function initializeHidePremiumTeaser() {
api.storage.sync.get(["hidePremiumTeaser"], (res) => {
if (res.hidePremiumTeaser === undefined) {
api.storage.sync.set({ hidePremiumTeaser: false });
extConfig.hidePremiumTeaser = false;
} else {
extConfig.hidePremiumTeaser = res.hidePremiumTeaser === true;
}
});
}
function isChrome() {
return typeof chrome !== "undefined" && typeof chrome.runtime !== "undefined";
}