Skip to content

Commit

Permalink
Fix worker hook #236
Browse files Browse the repository at this point in the history
- Inject into every worker
- Remove unused proxy code from vaft
- Add additional source stream request to vaft
- Make log inside hookWorkerFetch consistent between vaft/video-swap-new
  • Loading branch information
pixeltris committed Apr 12, 2024
1 parent 726254a commit 044d1fb
Show file tree
Hide file tree
Showing 4 changed files with 84 additions and 204 deletions.
108 changes: 28 additions & 80 deletions vaft/vaft-ublock-origin.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,8 @@ twitch-videoad.js text/javascript
scope.ClientVersion = 'null';
scope.ClientSession = 'null';
scope.PlayerType2 = 'embed'; //Source
scope.PlayerType3 = 'autoplay'; //360p
scope.PlayerType3 = 'site'; //Source
scope.PlayerType4 = 'autoplay'; //360p
scope.CurrentChannelName = null;
scope.UsherParams = null;
scope.WasShowingAd = false;
Expand All @@ -68,30 +69,21 @@ twitch-videoad.js text/javascript
scope.StreamInfosByUrl = [];
scope.MainUrlByUrl = [];
scope.EncodingCacheTimeout = 60000;
scope.DefaultProxyType = null;
scope.DefaultForcedQuality = null;
scope.DefaultProxyQuality = null;
scope.ClientIntegrityHeader = null;
scope.AuthorizationHeader = null;
}
declareOptions(window);
var TwitchAdblockSettings = {
BannerVisible: true,
ForcedQuality: null,
ProxyType: null,
ProxyQuality: null,
};
var twitchMainWorker = null;
var twitchWorkers = [];
var adBlockDiv = null;
var OriginalVideoPlayerQuality = null;
var IsPlayerAutoQuality = null;
const oldWorker = window.Worker;
window.Worker = class Worker extends oldWorker {
constructor(twitchBlobUrl) {
if (twitchMainWorker) {
super(twitchBlobUrl);
return;
}
var jsURL = getWasmWorkerUrl(twitchBlobUrl);
if (typeof jsURL !== 'string') {
super(twitchBlobUrl);
Expand Down Expand Up @@ -132,7 +124,7 @@ twitch-videoad.js text/javascript
importScripts('${jsURL}');
`;
super(URL.createObjectURL(new Blob([newBlobStr])));
twitchMainWorker = this;
twitchWorkers.push(this);
this.onmessage = function(e) {
if (e.data.key == 'ShowAdBlockBanner') {
if (!TwitchAdblockSettings.BannerVisible) {
Expand Down Expand Up @@ -268,7 +260,7 @@ twitch-videoad.js text/javascript
return req.responseText.split("'")[1];
}
function hookWorkerFetch() {
console.log('Twitch adblocker is enabled');
console.log('hookWorkerFetch');
var realFetch = fetch;
fetch = async function(url, options) {
if (typeof url === 'string') {
Expand All @@ -282,6 +274,9 @@ twitch-videoad.js text/javascript
if (weaverText.includes(AdSignifier)) {
weaverText = await processM3U8(url, responseText, realFetch, PlayerType3);
}
if (weaverText.includes(AdSignifier)) {
weaverText = await processM3U8(url, responseText, realFetch, PlayerType4);
}
resolve(new Response(weaverText));
};
var send = function() {
Expand Down Expand Up @@ -413,9 +408,6 @@ twitch-videoad.js text/javascript
}
async function getStreamForResolution(streamInfo, resolutionInfo, encodingsM3u8, fallbackStreamStr, playerType, realFetch) {
var qualityOverride = null;
if (playerType === 'proxy') {
qualityOverride = TwitchAdblockSettings.ProxyQuality ? TwitchAdblockSettings.ProxyQuality : DefaultProxyQuality;
}
if (streamInfo.EncodingsM3U8Cache[playerType].Resolution != resolutionInfo.Resolution ||
streamInfo.EncodingsM3U8Cache[playerType].RequestTime < Date.now() - EncodingCacheTimeout) {
console.log(`Blocking ads (type:${playerType}, resolution:${resolutionInfo.Resolution}, frameRate:${resolutionInfo.FrameRate}, qualityOverride:${qualityOverride})`);
Expand Down Expand Up @@ -521,28 +513,6 @@ twitch-videoad.js text/javascript
Resolution: null
};
}
if (playerType === 'proxy') {
try {
var proxyType = TwitchAdblockSettings.ProxyType ? TwitchAdblockSettings.ProxyType : DefaultProxyType;
var encodingsM3u8Response = null;
/*var tempUrl = stripUnusedParams(MainUrlByUrl[url]);
const match = /(hls|vod)\/(.+?)$/gim.exec(tempUrl);*/
switch (proxyType) {
case 'TTV LOL':
encodingsM3u8Response = await realFetch('https://api.ttv.lol/playlist/' + CurrentChannelName + '.m3u8%3Fallow_source%3Dtrue'/* + encodeURIComponent(match[2])*/, {headers: {'X-Donate-To': 'https://ttv.lol/donate'}});
break;
/*case 'Purple Adblock':// Broken...
encodingsM3u8Response = await realFetch('https://eu1.jupter.ga/channel/' + CurrentChannelName);*/
case 'Falan':// https://greasyfork.org/en/scripts/425139-twitch-ad-fix/code
encodingsM3u8Response = await realFetch(atob('aHR0cHM6Ly9qaWdnbGUuYmV5cGF6YXJpZ3VydXN1LndvcmtlcnMuZGV2') + '/hls/' + CurrentChannelName + '.m3u8%3Fallow_source%3Dtrue'/* + encodeURIComponent(match[2])*/);
break;
}
if (encodingsM3u8Response && encodingsM3u8Response.status === 200) {
return getStreamForResolution(streamInfo, currentResolution, await encodingsM3u8Response.text(), textStr, playerType, realFetch);
}
} catch (err) {}
return textStr;
}
var accessTokenResponse = await getAccessToken(CurrentChannelName, playerType);
if (accessTokenResponse.status === 200) {
var accessToken = await accessTokenResponse.json();
Expand Down Expand Up @@ -798,27 +768,23 @@ twitch-videoad.js text/javascript
} catch (err) {}
} catch (err) {}
}
window.reloadTwitchPlayer = doTwitchPlayerTask;
var localDeviceID = null;
localDeviceID = window.localStorage.getItem('local_copy_unique_id');
function postTwitchWorkerMessage(key, value) {
twitchWorkers.forEach((worker) => {
worker.postMessage({key: key, value: value});
});
}
function hookFetch() {
var realFetch = window.fetch;
window.fetch = function(url, init, ...args) {
if (typeof url === 'string') {
//Check if squad stream.
if (window.location.pathname.includes('/squad')) {
if (twitchMainWorker) {
twitchMainWorker.postMessage({
key: 'UpdateIsSquadStream',
value: true
});
}
postTwitchWorkerMessage('UpdateIsSquadStream', true);
} else {
if (twitchMainWorker) {
twitchMainWorker.postMessage({
key: 'UpdateIsSquadStream',
value: false
});
}
postTwitchWorkerMessage('UpdateIsSquadStream', false);
}
if (url.includes('/access_token') || url.includes('gql')) {
//Device ID is used when notifying Twitch of ads.
Expand All @@ -833,39 +799,30 @@ twitch-videoad.js text/javascript
GQLDeviceID = localDeviceID.replace('"', '');
GQLDeviceID = GQLDeviceID.replace('"', '');
}
if (GQLDeviceID && twitchMainWorker) {
if (GQLDeviceID) {
if (typeof init.headers['X-Device-Id'] === 'string') {
init.headers['X-Device-Id'] = GQLDeviceID;
}
if (typeof init.headers['Device-ID'] === 'string') {
init.headers['Device-ID'] = GQLDeviceID;
}
twitchMainWorker.postMessage({
key: 'UpdateDeviceId',
value: GQLDeviceID
});
postTwitchWorkerMessage('UpdateDeviceId', GQLDeviceID);
}
//Client version is used in GQL requests.
var clientVersion = init.headers['Client-Version'];
if (clientVersion && typeof clientVersion == 'string') {
ClientVersion = clientVersion;
}
if (ClientVersion && twitchMainWorker) {
twitchMainWorker.postMessage({
key: 'UpdateClientVersion',
value: ClientVersion
});
if (ClientVersion) {
postTwitchWorkerMessage('UpdateClientVersion', ClientVersion);
}
//Client session is used in GQL requests.
var clientSession = init.headers['Client-Session-Id'];
if (clientSession && typeof clientSession == 'string') {
ClientSession = clientSession;
}
if (ClientSession && twitchMainWorker) {
twitchMainWorker.postMessage({
key: 'UpdateClientSession',
value: ClientSession
});
if (ClientSession) {
postTwitchWorkerMessage('UpdateClientSession', ClientSession);
}
//Client ID is used in GQL requests.
if (url.includes('gql') && init && typeof init.body === 'string' && init.body.includes('PlaybackAccessToken')) {
Expand All @@ -878,27 +835,18 @@ twitch-videoad.js text/javascript
ClientID = clientId;
}
}
if (ClientID && twitchMainWorker) {
twitchMainWorker.postMessage({
key: 'UpdateClientId',
value: ClientID
});
if (ClientID) {
postTwitchWorkerMessage('UpdateClientId', ClientID);
}
//Client integrity header
ClientIntegrityHeader = init.headers['Client-Integrity'];
if (ClientIntegrityHeader && twitchMainWorker) {
twitchMainWorker.postMessage({
key: 'UpdateClientIntegrityHeader',
value: init.headers['Client-Integrity']
});
if (ClientIntegrityHeader) {
postTwitchWorkerMessage('UpdateClientIntegrityHeader', ClientIntegrityHeader);
}
//Authorization header
AuthorizationHeader = init.headers['Authorization'];
if (AuthorizationHeader && twitchMainWorker) {
twitchMainWorker.postMessage({
key: 'UpdateAuthorizationHeader',
value: init.headers['Authorization']
});
if (AuthorizationHeader) {
postTwitchWorkerMessage('UpdateAuthorizationHeader', AuthorizationHeader);
}
}
//To prevent pause/resume loop for mid-rolls.
Expand Down
Loading

0 comments on commit 044d1fb

Please sign in to comment.