Add WIP implementation of #177

This commit is contained in:
younesaassila 2025-01-31 23:07:37 +01:00
parent aaf1961913
commit 3536898e23
8 changed files with 207 additions and 56 deletions

View File

@ -0,0 +1,12 @@
import store from "../../store";
export default function wasChannelSubscriber(
channelName: string | null
): boolean {
if (!channelName) return false;
const activeChannelSubscriptionsLower =
store.state.activeChannelSubscriptions.map(channel =>
channel.toLowerCase()
);
return activeChannelSubscriptionsLower.includes(channelName.toLowerCase());
}

View File

@ -2,8 +2,10 @@ import pageScriptURL from "url:../page/page.ts";
import workerScriptURL from "url:../page/worker.ts"; import workerScriptURL from "url:../page/worker.ts";
import browser, { Storage } from "webextension-polyfill"; import browser, { Storage } from "webextension-polyfill";
import findChannelFromTwitchTvUrl from "../common/ts/findChannelFromTwitchTvUrl"; import findChannelFromTwitchTvUrl from "../common/ts/findChannelFromTwitchTvUrl";
import isChannelWhitelisted from "../common/ts/isChannelWhitelisted";
import isChromium from "../common/ts/isChromium"; import isChromium from "../common/ts/isChromium";
import { getStreamStatus, setStreamStatus } from "../common/ts/streamStatus"; import { getStreamStatus, setStreamStatus } from "../common/ts/streamStatus";
import wasChannelSubscriber from "../common/ts/wasChannelSubscriber";
import store from "../store"; import store from "../store";
import type { State } from "../store/types"; import type { State } from "../store/types";
import { MessageType } from "../types"; import { MessageType } from "../types";
@ -64,6 +66,7 @@ function onStoreChange(changes: Record<string, Storage.StorageChange>) {
// This is mainly to reduce the amount of messages sent to the page script. // This is mainly to reduce the amount of messages sent to the page script.
// (Also to reduce the number of console logs.) // (Also to reduce the number of console logs.)
const ignoredKeys: (keyof State)[] = [ const ignoredKeys: (keyof State)[] = [
"activeChannelSubscriptions",
"adLog", "adLog",
"dnsResponses", "dnsResponses",
"openedTwitchTabs", "openedTwitchTabs",
@ -102,61 +105,117 @@ function onPageMessage(event: MessageEvent) {
const message = event.data?.message; const message = event.data?.message;
if (!message) return; if (!message) return;
switch (message.type) { // GetStoreState
case MessageType.GetStoreState: if (message.type === MessageType.GetStoreState) {
const sendStoreState = () => { const sendStoreState = () => {
window.postMessage({ window.postMessage({
type: MessageType.PageScriptMessage, type: MessageType.PageScriptMessage,
message: { message: {
type: MessageType.GetStoreStateResponse, type: MessageType.GetStoreStateResponse,
state: JSON.parse(JSON.stringify(store.state)), state: JSON.parse(JSON.stringify(store.state)),
}, },
});
};
if (store.readyState === "complete") sendStoreState();
else store.addEventListener("load", sendStoreState);
break;
case MessageType.EnableFullMode:
try {
browser.runtime.sendMessage(message);
} catch (error) {
console.error(
"[TTV LOL PRO] Failed to send EnableFullMode message",
error
);
}
break;
case MessageType.DisableFullMode:
try {
browser.runtime.sendMessage(message);
} catch (error) {
console.error(
"[TTV LOL PRO] Failed to send DisableFullMode message",
error
);
}
break;
case MessageType.UsherResponse:
try {
browser.runtime.sendMessage(message);
} catch (error) {
console.error(
"[TTV LOL PRO] Failed to send UsherResponse message",
error
);
}
break;
case MessageType.MultipleAdBlockersInUse:
const channelName = findChannelFromTwitchTvUrl(location.href);
if (!channelName) break;
const streamStatus = getStreamStatus(channelName);
setStreamStatus(channelName, {
...(streamStatus ?? { proxied: false }),
reason: "Another Twitch ad blocker is in use",
}); });
break; };
case MessageType.ClearStats: if (store.readyState === "complete") sendStoreState();
clearStats(message.channelName); else store.addEventListener("load", sendStoreState);
break; }
// EnableFullMode
else if (message.type === MessageType.EnableFullMode) {
try {
browser.runtime.sendMessage(message);
} catch (error) {
console.error(
"[TTV LOL PRO] Failed to send EnableFullMode message",
error
);
}
}
// DisableFullMode
else if (message.type === MessageType.DisableFullMode) {
try {
browser.runtime.sendMessage(message);
} catch (error) {
console.error(
"[TTV LOL PRO] Failed to send DisableFullMode message",
error
);
}
}
// ChannelSubscriptionStatus
else if (message.type === MessageType.ChannelSubscriptionStatus) {
const { channelName, isSubscribed, scope } = message;
const wasSubscribed = wasChannelSubscriber(channelName);
let isWhitelisted = isChannelWhitelisted(channelName);
console.log(
"[TTV LOL PRO] Received channel subscription status message. Current state:",
{
wasSubscribed,
isSubscribed,
isWhitelisted,
}
);
if (store.state.whitelistChannelSubscriptions && channelName != null) {
if (!wasSubscribed && isSubscribed) {
store.state.activeChannelSubscriptions.push(channelName);
// Add to whitelist.
if (!isWhitelisted) {
console.log(`[TTV LOL PRO] Adding '${channelName}' to whitelist.`);
store.state.whitelistedChannels.push(channelName);
isWhitelisted = true;
}
} else if (wasSubscribed && !isSubscribed) {
store.state.activeChannelSubscriptions =
store.state.activeChannelSubscriptions.filter(
c => c.toLowerCase() !== channelName.toLowerCase()
);
// Remove from whitelist.
if (isWhitelisted) {
console.log(
`[TTV LOL PRO] Removing '${channelName}' from whitelist.`
);
store.state.whitelistedChannels =
store.state.whitelistedChannels.filter(
c => c.toLowerCase() !== channelName.toLowerCase()
);
isWhitelisted = false;
}
}
}
console.log("[TTV LOL PRO] Sending channel subscription status response.");
window.postMessage({
type:
scope === "page" // TODO: Is this necessary? Isn't the scope always "worker"?
? MessageType.PageScriptMessage
: MessageType.WorkerScriptMessage,
message: {
type: MessageType.ChannelSubscriptionStatusResponse,
isWhitelisted: isWhitelisted,
},
});
}
// UsherResponse
else if (message.type === MessageType.UsherResponse) {
try {
browser.runtime.sendMessage(message);
} catch (error) {
console.error(
"[TTV LOL PRO] Failed to send UsherResponse message",
error
);
}
}
// MultipleAdBlockersInUse
else if (message.type === MessageType.MultipleAdBlockersInUse) {
const channelName = findChannelFromTwitchTvUrl(location.href);
if (!channelName) return;
const streamStatus = getStreamStatus(channelName);
setStreamStatus(channelName, {
...(streamStatus ?? { proxied: false }),
reason: "Another Twitch ad blocker is in use",
});
}
// ClearStats
else if (message.type === MessageType.ClearStats) {
clearStats(message.channelName);
} }
} }

View File

@ -75,6 +75,9 @@ const passportLevelProxyUsageWwwElement = $(
const whitelistedChannelsListElement = $( const whitelistedChannelsListElement = $(
"#whitelisted-channels-list" "#whitelisted-channels-list"
) as HTMLUListElement; ) as HTMLUListElement;
const whitelistSubscriptionsCheckboxElement = $(
"#whitelist-subscriptions-checkbox"
) as HTMLInputElement;
// Proxies // Proxies
const optimizedProxiesInputElement = $("#optimized") as HTMLInputElement; const optimizedProxiesInputElement = $("#optimized") as HTMLInputElement;
const optimizedProxiesListElement = $( const optimizedProxiesListElement = $(
@ -163,6 +166,12 @@ function main() {
return [true]; return [true];
}, },
}); });
whitelistSubscriptionsCheckboxElement.checked =
store.state.whitelistChannelSubscriptions;
whitelistSubscriptionsCheckboxElement.addEventListener("change", () => {
store.state.whitelistChannelSubscriptions =
whitelistSubscriptionsCheckboxElement.checked;
});
// Proxies // Proxies
if (store.state.optimizedProxiesEnabled) if (store.state.optimizedProxiesEnabled)
optimizedProxiesInputElement.checked = true; optimizedProxiesInputElement.checked = true;
@ -548,6 +557,7 @@ exportButtonElement.addEventListener("click", () => {
optimizedProxies: store.state.optimizedProxies, optimizedProxies: store.state.optimizedProxies,
optimizedProxiesEnabled: store.state.optimizedProxiesEnabled, optimizedProxiesEnabled: store.state.optimizedProxiesEnabled,
passportLevel: store.state.passportLevel, passportLevel: store.state.passportLevel,
whitelistChannelSubscriptions: store.state.whitelistChannelSubscriptions,
whitelistedChannels: store.state.whitelistedChannels, whitelistedChannels: store.state.whitelistedChannels,
}; };
saveFile( saveFile(

View File

@ -138,6 +138,23 @@
Twitch tabs are whitelisted channels. Twitch tabs are whitelisted channels.
</small> </small>
<ul id="whitelisted-channels-list" class="store-list"></ul> <ul id="whitelisted-channels-list" class="store-list"></ul>
<ul class="options-list">
<li>
<input
type="checkbox"
name="whitelist-subscriptions-checkbox"
id="whitelist-subscriptions-checkbox"
/>
<label for="whitelist-subscriptions-checkbox">
Automatically whitelist channels you're subscribed to
</label>
<br />
<small>
This option will automatically add or remove channels from the
whitelist based on your subscriptions.
</small>
</li>
</ul>
</section> </section>
<!-- Proxies --> <!-- Proxies -->

View File

@ -265,7 +265,42 @@ export function getFetch(pageState: PageState): typeof fetch {
encodeURIComponent('"player_type":"frontpage"') encodeURIComponent('"player_type":"frontpage"')
); );
const channelName = findChannelFromUsherUrl(url); const channelName = findChannelFromUsherUrl(url);
const isWhitelisted = isChannelWhitelisted(channelName, pageState); let isWhitelisted = isChannelWhitelisted(channelName, pageState);
if (
pageState.state?.whitelistChannelSubscriptions &&
channelName != null
) {
const wasSubscribed = wasChannelSubscriber(channelName, pageState);
const isSubscribed = url.includes(
encodeURIComponent('"subscriber":true')
);
// const isSubscribed = url.includes(
// encodeURIComponent("aminematue")
// );
const hasSubStatusChanged =
(wasSubscribed && !isSubscribed) || (!wasSubscribed && isSubscribed);
if (hasSubStatusChanged) {
console.log(
"[TTV LOL PRO] Channel subscription status changed. Sending message…"
);
try {
const response =
await pageState.sendMessageToContentScriptAndWaitForResponse(
pageState.scope,
{
type: MessageType.ChannelSubscriptionStatus,
scope: pageState.scope,
channelName,
isSubscribed,
},
MessageType.ChannelSubscriptionStatusResponse
);
if (typeof response.isWhitelisted === "boolean") {
isWhitelisted = response.isWhitelisted;
}
} catch {}
}
}
if (!isLivestream || isFrontpage || isWhitelisted) { if (!isLivestream || isFrontpage || isWhitelisted) {
console.log( console.log(
"[TTV LOL PRO] Not flagging Usher request: not a livestream, is frontpage, or is whitelisted." "[TTV LOL PRO] Not flagging Usher request: not a livestream, is frontpage, or is whitelisted."
@ -623,6 +658,18 @@ function isChannelWhitelisted(
return whitelistedChannelsLower.includes(channelName.toLowerCase()); return whitelistedChannelsLower.includes(channelName.toLowerCase());
} }
function wasChannelSubscriber(
channelName: string | null | undefined,
pageState: PageState
): boolean {
if (!channelName) return false;
const activeChannelSubscriptionsLower =
pageState.state?.activeChannelSubscriptions.map(channel =>
channel.toLowerCase()
) ?? [];
return activeChannelSubscriptionsLower.includes(channelName.toLowerCase());
}
async function flagRequest( async function flagRequest(
request: Request, request: Request,
requestType: ProxyRequestType, requestType: ProxyRequestType,

View File

@ -3,6 +3,7 @@ import type { State } from "./types";
export default function getDefaultState() { export default function getDefaultState() {
const state: State = { const state: State = {
activeChannelSubscriptions: [],
adLog: [], adLog: [],
adLogEnabled: true, adLogEnabled: true,
adLogLastSent: 0, adLogLastSent: 0,
@ -18,6 +19,7 @@ export default function getDefaultState() {
passportLevel: 0, passportLevel: 0,
streamStatuses: {}, streamStatuses: {},
videoWeaverUrlsByChannel: {}, videoWeaverUrlsByChannel: {},
whitelistChannelSubscriptions: true,
whitelistedChannels: [], whitelistedChannels: [],
}; };
return state; return state;

View File

@ -6,6 +6,7 @@ export type ReadyState = "loading" | "complete";
export type StorageAreaName = "local" | "managed" | "sync"; export type StorageAreaName = "local" | "managed" | "sync";
export interface State { export interface State {
activeChannelSubscriptions: string[];
adLog: AdLogEntry[]; adLog: AdLogEntry[];
adLogEnabled: boolean; adLogEnabled: boolean;
adLogLastSent: number; adLogLastSent: number;
@ -19,6 +20,7 @@ export interface State {
passportLevel: number; passportLevel: number;
streamStatuses: Record<string, StreamStatus>; streamStatuses: Record<string, StreamStatus>;
videoWeaverUrlsByChannel: Record<string, string[]>; videoWeaverUrlsByChannel: Record<string, string[]>;
whitelistChannelSubscriptions: boolean;
whitelistedChannels: string[]; whitelistedChannels: string[];
} }

View File

@ -79,6 +79,8 @@ export const enum MessageType {
EnableFullMode = "TLP_EnableFullMode", EnableFullMode = "TLP_EnableFullMode",
EnableFullModeResponse = "TLP_EnableFullModeResponse", EnableFullModeResponse = "TLP_EnableFullModeResponse",
DisableFullMode = "TLP_DisableFullMode", DisableFullMode = "TLP_DisableFullMode",
ChannelSubscriptionStatus = "TLP_ChannelSubscriptionStatus",
ChannelSubscriptionStatusResponse = "TLP_ChannelSubscriptionStatusResponse",
UsherResponse = "TLP_UsherResponse", UsherResponse = "TLP_UsherResponse",
NewPlaybackAccessToken = "TLP_NewPlaybackAccessToken", NewPlaybackAccessToken = "TLP_NewPlaybackAccessToken",
NewPlaybackAccessTokenResponse = "TLP_NewPlaybackAccessTokenResponse", NewPlaybackAccessTokenResponse = "TLP_NewPlaybackAccessTokenResponse",