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

TW-1180: Replace existing ads to slise xyz #1025

Merged
merged 8 commits into from
Dec 5, 2023
Merged
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 .browserslistrc
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[production]
chrome >= 49
chrome >= 103
firefox >= 52
opera >= 36
safari >= 14
Expand Down
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,6 @@
"webextension-polyfill": "^0.10.0",
"webpack": "^5.74.0",
"webpack-cli": "^5",
"webpack-ext-reloader": "^1.1.9",
"webpack-ext-reloader-mv3": "^2.1.1",
"webpack-target-webextension": "^1.0.4",
"webpackbar": "^5",
Expand Down
16 changes: 15 additions & 1 deletion src/lib/constants.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,21 @@
export enum ContentScriptType {
ExternalLinksActivity = 'ExternalLinksActivity'
ExternalLinksActivity = 'ExternalLinksActivity',
ExternalAdsActivity = 'ExternalAdsActivity'
}

export enum AdType {
EtherscanBuiltin = 'etherscan-builtin',
Bitmedia = 'bitmedia',
Coinzilla = 'coinzilla',
Cointraffic = 'cointraffic'
}

export const WEBSITES_ANALYTICS_ENABLED = 'WEBSITES_ANALYTICS_ENABLED';

export const ACCOUNT_PKH_STORAGE_KEY = 'account_publickeyhash';

export const ETHERSCAN_BUILTIN_ADS_WEBSITES = [
'https://etherscan.io',
'https://bscscan.com',
'https://polygonscan.com'
];
80 changes: 60 additions & 20 deletions src/lib/slise/get-ads-containers.ts
Original file line number Diff line number Diff line change
@@ -1,41 +1,81 @@
import { AdType, ETHERSCAN_BUILTIN_ADS_WEBSITES } from 'lib/constants';

interface AdContainerProps {
element: HTMLElement;
width: number;
height: number;
type: AdType;
}

const getFinalWidth = (element: Element) => {
const getFinalSize = (element: Element) => {
const elementStyle = getComputedStyle(element);
const rawWidthFromStyle = elementStyle.width;
const rawWidthFromAttribute = element.getAttribute('width');
const size = { width: 0, height: 0 };
const dimensions = ['width', 'height'] as const;

for (const dimension of dimensions) {
const rawDimensionFromStyle = elementStyle[dimension];
const rawDimensionFromAttribute = element.getAttribute(dimension);
const rawDimension = rawDimensionFromAttribute || rawDimensionFromStyle;

if (/\d+px/.test(rawDimension)) {
size[dimension] = Number(rawDimension.replace('px', ''));
} else {
size[dimension] = dimension === 'width' ? element.clientWidth : element.clientHeight;
}
}

return Number((rawWidthFromAttribute || rawWidthFromStyle).replace('px', '') || element.clientWidth);
return size;
};

const mapBannersWithType = (banners: NodeListOf<Element>, type: AdType) =>
[...banners].map(banner => ({ banner, type }));

export const getAdsContainers = () => {
const builtInAdsImages = [...document.querySelectorAll('span + img')].filter(element => {
const { width, height } = element.getBoundingClientRect();
const label = element.previousElementSibling?.innerHTML ?? '';
const locationUrl = window.parent.location.href;
const builtInAdsImages = ETHERSCAN_BUILTIN_ADS_WEBSITES.some(urlPrefix => locationUrl.startsWith(urlPrefix))
? [...document.querySelectorAll('span + img')].filter(element => {
const { width, height } = element.getBoundingClientRect();
const label = element.previousElementSibling?.innerHTML ?? '';

return (width > 0 || height > 0) && ['Featured', 'Ad'].includes(label);
});
const coinzillaBanners = [...document.querySelectorAll('.coinzilla')];
const bitmediaBanners = [...document.querySelectorAll('iframe[src*="media.bmcdn"], iframe[src*="cdn.bmcdn"]')];
return (width > 0 || height > 0) && ['Featured', 'Ad'].includes(label);
})
: [];
const coinzillaBanners = mapBannersWithType(
document.querySelectorAll('iframe[src*="coinzilla.io"], iframe[src*="czilladx.com"]'),
AdType.Coinzilla
);
const bitmediaBanners = mapBannersWithType(
document.querySelectorAll('iframe[src*="media.bmcdn"], iframe[src*="cdn.bmcdn"]'),
AdType.Bitmedia
);
const cointrafficBanners = mapBannersWithType(
document.querySelectorAll('iframe[src*="ctengine.io"]'),
AdType.Cointraffic
);

return builtInAdsImages
.map((image): AdContainerProps | null => {
const element = image.closest('div');

return element && { element, width: getFinalWidth(image) };
return (
element && {
...getFinalSize(image),
element,
type: AdType.EtherscanBuiltin
}
);
})
.concat(
[...bitmediaBanners, ...coinzillaBanners].map(banner => {
const parentElement = banner.parentElement;
const closestDiv = parentElement?.closest('div') ?? null;
const element = bitmediaBanners.includes(banner) ? closestDiv : parentElement;
const widthDefinedElement = element?.parentElement ?? parentElement;
const bannerFrame = banner.tagName === 'iframe' ? banner : banner.querySelector('iframe');

return element && { element, width: getFinalWidth(bannerFrame || widthDefinedElement!) };
[...bitmediaBanners, ...coinzillaBanners, ...cointrafficBanners].map(({ banner, type }) => {
const element = banner.parentElement?.closest('div') ?? null;

return (
element && {
...getFinalSize(banner),
element,
type
}
);
})
)
.filter((element): element is AdContainerProps => Boolean(element));
Expand Down
6 changes: 4 additions & 2 deletions src/lib/slise/get-slot-id.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
export const getSlotId = () => {
const hostnameParts = window.location.hostname.split('.').filter(part => part !== 'www');
const hostnameParts = window.parent.location.hostname.split('.').filter(part => part !== 'www');
const serviceId = hostnameParts[0];
const pathnameParts = window.location.pathname.split('/').filter(part => part !== '' && !/0x[0-9a-f]+/i.test(part));
const pathnameParts = window.parent.location.pathname
.split('/')
.filter(part => part !== '' && !/^(0x)?[0-9a-f]+$/i.test(part) && !/^[0-9a-z]{30,}$/i.test(part));

return [serviceId, ...pathnameParts].join('-');
};
8 changes: 7 additions & 1 deletion src/lib/slise/slise-ad.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,18 @@ import { SliseAd as OriginalSliseAd, SliseAdProps } from '@slise/embed-react';

import { useDidMount } from 'lib/ui/hooks/useDidMount';

import { getSlotId } from './get-slot-id';

interface CunningSliseAdProps extends Omit<SliseAdProps, 'format' | 'style'> {
width: number;
height: number;
}

export const SliseAd = memo(({ width, height, ...restProps }: CunningSliseAdProps) => {
export const buildSliceAdReactNode = (width: number, height: number) => (
<SliseAd slotId={getSlotId()} pub="pub-25" width={width} height={height} />
);

const SliseAd = memo(({ width, height, ...restProps }: CunningSliseAdProps) => {
useDidMount(() => require('./slise-ad.embed'));

return <OriginalSliseAd {...restProps} format={`${width}x${height}`} style={{ width, height }} />;
Expand Down
32 changes: 19 additions & 13 deletions src/lib/temple/back/main.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import browser, { Runtime } from 'webextension-polyfill';

import { ACCOUNT_PKH_STORAGE_KEY, ContentScriptType } from 'lib/constants';
import { E2eMessageType } from 'lib/e2e/types';
import { BACKGROUND_IS_WORKER } from 'lib/env';
import { encodeMessage, encryptMessage, getSenderId, MessageType, Response } from 'lib/temple/beacon';
import { clearAsyncStorages } from 'lib/temple/reset';
import { TempleMessageType, TempleRequest, TempleResponse } from 'lib/temple/types';
import { getTrackedUrl } from 'lib/utils/url-track/get-tracked-url';

import { ACCOUNT_PKH_STORAGE_KEY, ContentScriptType } from '../../constants';
import * as Actions from './actions';
import * as Analytics from './analytics';
import { intercom } from './defaults';
Expand Down Expand Up @@ -245,24 +245,30 @@ const processRequest = async (req: TempleRequest, port: Runtime.Port): Promise<T
};

browser.runtime.onMessage.addListener(msg => {
if (msg?.type === ContentScriptType.ExternalLinksActivity) {
const url = getTrackedUrl(msg.url);
switch (msg?.type) {
case ContentScriptType.ExternalLinksActivity:
const url = getTrackedUrl(msg.url);

if (url) {
browser.storage.local
.get(ACCOUNT_PKH_STORAGE_KEY)
.then(({ [ACCOUNT_PKH_STORAGE_KEY]: accountPkh }) =>
Analytics.client.track('External links activity', { url, accountPkh })
)
.catch(console.error);
}

if (url) {
break;
case ContentScriptType.ExternalAdsActivity:
browser.storage.local
.get(ACCOUNT_PKH_STORAGE_KEY)
.then(({ [ACCOUNT_PKH_STORAGE_KEY]: accountPkh }) =>
Analytics.client.track('External links activity', { url, accountPkh })
Analytics.client.track('External Ads Activity', { url: msg.url, accountPkh })
)
.catch(console.error);
}
}

if (msg?.type === E2eMessageType.ResetRequest) {
return new Promise(async resolve => {
await clearAsyncStorages();
resolve({ type: E2eMessageType.ResetResponse });
});
break;
case E2eMessageType.ResetRequest:
return clearAsyncStorages().then(() => ({ type: E2eMessageType.ResetResponse }));
}

return;
Expand Down
81 changes: 81 additions & 0 deletions src/replaceAds.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import browser from 'webextension-polyfill';

import { AdType, ContentScriptType, ETHERSCAN_BUILTIN_ADS_WEBSITES, WEBSITES_ANALYTICS_ENABLED } from 'lib/constants';
import { getAdsContainers } from 'lib/slise/get-ads-containers';

const availableAdsResolutions = [
{ width: 270, height: 90 },
{ width: 728, height: 90 }
];

let oldHref = '';

let processing = false;

const replaceAds = async () => {
if (processing) return;
processing = true;

try {
const adsContainers = getAdsContainers();
const adsContainersToReplace = adsContainers.filter(
({ width, height }) =>
((width >= 600 && width <= 900) || (width >= 180 && width <= 430)) && height >= 60 && height <= 120
);

const newHref = window.parent.location.href;
if (oldHref !== newHref && adsContainersToReplace.length > 0) {
oldHref = newHref;

browser.runtime.sendMessage({
type: ContentScriptType.ExternalAdsActivity,
url: window.parent.location.origin
});
}

if (!adsContainersToReplace.length) {
processing = false;
return;
}

const ReactDomModule = await import('react-dom/client');
const SliceAdModule = await import('lib/slise/slise-ad');

adsContainersToReplace.forEach(({ element: adContainer, width: containerWidth, type }) => {
let adsResolution = availableAdsResolutions[0];
for (let i = 1; i < availableAdsResolutions.length; i++) {
const candidate = availableAdsResolutions[i];
if (candidate.width <= containerWidth && candidate.width > adsResolution.width) {
adsResolution = candidate;
}
}

if (
ETHERSCAN_BUILTIN_ADS_WEBSITES.some(urlPrefix => newHref.startsWith(urlPrefix)) &&
type === AdType.Coinzilla
) {
adContainer.style.textAlign = 'left';
}

const adRoot = ReactDomModule.createRoot(adContainer);
adRoot.render(SliceAdModule.buildSliceAdReactNode(adsResolution.width, adsResolution.height));
});
} catch (error) {
console.error('Replacing Ads error:', error);
}

processing = false;
};

// Prevents the script from running in an Iframe
if (window.frameElement === null) {
browser.storage.local.get(WEBSITES_ANALYTICS_ENABLED).then(storage => {
if (storage[WEBSITES_ANALYTICS_ENABLED]) {
// Replace ads with those from Slise
window.addEventListener('load', () => replaceAds());
window.addEventListener('ready', () => replaceAds());
setInterval(() => replaceAds(), 1000);
replaceAds();
}
});
}
53 changes: 0 additions & 53 deletions src/replaceAds.tsx

This file was deleted.

Loading
Loading