Removes google ads from codebase, fix analytics (#403)

This commit is contained in:
Geometrically 2022-03-07 19:01:38 -07:00 committed by GitHub
parent 91b79b703c
commit e87d85b088
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
12 changed files with 10 additions and 607 deletions

View File

@ -1,16 +1,5 @@
<template> <template>
<div v-if="displayed && !hidden" class="ad-wrapper"> <div v-if="ethical_ads_on">
<div class="ad">
<GptAd
:key="format.adUnit"
ref="ad_slot"
:ad-unit="format.adUnit"
:size="format.size"
:is-responsive="true"
/>
</div>
</div>
<div v-else-if="ethical_ads_on">
<div v-if="ethical_ad_display && ethicalAdType === 'text'"> <div v-if="ethical_ad_display && ethicalAdType === 'text'">
<div <div
:class="ethical_ad_style" :class="ethical_ad_style"

View File

@ -1,21 +1,17 @@
import axios from 'axios'
export default function (context) { export default function (context) {
if (process.client && context.from.path === context.route.path) {
return
}
if (context.$config.analytics.base_url == null) { if (context.$config.analytics.base_url == null) {
return return
} }
let domain = ''
if (process.server) {
domain = context.req.headers.host
} else {
domain = location.host
}
const url = context.$config.analytics.base_url + '/register/visit'
const path = context.route.path.split('?')[0]
setTimeout(() => { setTimeout(() => {
axios context.$axios
.post(url, { .post(`${context.$config.analytics.base_url}/register/visit`, {
path, path: context.route.path,
domain, domain: process.server ? context.req.headers.host : location.host,
consent: false, consent: false,
}) })
.then(() => {}) .then(() => {})

View File

@ -1,6 +0,0 @@
export const DEFAULT_OPTIONS = {
enabled: false,
script_url: 'https://static.cloudflareinsights.com/beacon.min.js',
token: 'xxx',
}
export const CF_LIB_TAG_ID = 'cf-import'

View File

@ -1,24 +0,0 @@
import { DEFAULT_OPTIONS, CF_LIB_TAG_ID } from './constants'
const { resolve } = require('path')
// eslint-disable-next-line require-await
module.exports = async function module(moduleOptions) {
const options = Object.assign(
DEFAULT_OPTIONS,
this.options.analytics,
moduleOptions
)
const templatesOptions = {
...options,
CF_LIB_TAG_ID,
}
this.addPlugin({
src: resolve(__dirname, 'templates/plugin.js'),
fileName: 'analytics/plugin.js',
options: templatesOptions,
})
}
module.exports.meta = require('../package.json')

View File

@ -1,37 +0,0 @@
// eslint-disable-next-line require-await
export default async function (ctx, inject) {
const config = (ctx.$config && ctx.$config.analytics) || {}
const url = config.script_url ?? '<%= options.script_url %>'
const tag = config.token ?? '<%= options.token %>'
// eslint-disable-next-line
const enabled = config.enabled ?? ('<%= options.enabled || false %>' === 'true');
// Check if the parameters are not changed by runtime config:
const UNAMI_LIB_TAG_ID = '<%= options.UNAMI_LIB_TAG_ID %>'
if (!enabled) {
return
}
const injectScript = (script) => {
const scriptIndex = ctx.app.head.script.findIndex(
(s) => s.hid === script.hid
)
if (scriptIndex !== -1) {
ctx.app.head.script[scriptIndex] = script
} else {
ctx.app.head.script.push(script)
}
}
const analyticsScript = {
hid: UNAMI_LIB_TAG_ID,
src: url,
'data-cf-beacon': JSON.stringify({
token: tag,
spa: true,
}),
defer: true,
}
injectScript(analyticsScript)
}

View File

@ -1,31 +0,0 @@
{
"name": "@modrinth/analytics",
"version": "0.1.0",
"description": "Cloudflare analytics integration for Nuxtjs",
"license": "MIT",
"contributors": [
{
"name": "redblueflame <contact@redblueflame.com>"
}
],
"main": "lib/module.js",
"repository": "https://github.com/modrinth/knossos/",
"homepage": "https://github.com/modrinth/knossos/tree/master/modules/analytics",
"files": [
"lib"
],
"devDependencies": {
"codecov": "latest",
"eslint": "5.13.0",
"eslint-config-airbnb-base": "13.1.0",
"eslint-loader": "2.1.2",
"eslint-plugin-import": "2.16.0",
"eslint-plugin-jest": "22.3.0",
"eslint-plugin-vue": "5.2.1",
"jest": "24.1.0",
"jsdom": "14.0.0",
"nuxt": "2.4.3",
"request-promise-native": "1.0.5",
"standard-version": "latest"
}
}

View File

@ -1,16 +0,0 @@
export const DEFAULT_OPTIONS = {
networkCode: null,
debug: false,
ghostMode: false,
componentName: 'GptAd',
individualRefresh: false,
responsive: false,
collapseEmptyDivs: false,
emptyClass: 'is-empty',
geoEdgeId: '',
}
export const GPT_LIB_SCRIPT_ID = 'google-publisher-tag-lib-script'
export const GPT_INIT_SCRIPT_ID = 'google-publisher-tag-init-script'
export const GEOEDGE_CONF_SCRIPT_ID = 'geoedge-config-script'
export const GEOEDGE_LIB_SCRIPT_ID = 'geoedge-lib-script'

View File

@ -1,39 +0,0 @@
import {
DEFAULT_OPTIONS,
GPT_LIB_SCRIPT_ID,
GPT_INIT_SCRIPT_ID,
GEOEDGE_CONF_SCRIPT_ID,
GEOEDGE_LIB_SCRIPT_ID,
} from './constants'
const { resolve } = require('path')
// eslint-disable-next-line require-await
module.exports = async function module(moduleOptions) {
const options = Object.assign(
DEFAULT_OPTIONS,
this.options.ads,
moduleOptions
)
const templatesOptions = {
...options,
GPT_LIB_SCRIPT_ID,
GPT_INIT_SCRIPT_ID,
GEOEDGE_CONF_SCRIPT_ID,
GEOEDGE_LIB_SCRIPT_ID,
}
this.addPlugin({
src: resolve(__dirname, 'templates/plugin.js'),
fileName: 'gpt-ads-module/plugin.js',
options: templatesOptions,
})
this.addTemplate({
src: resolve(__dirname, 'templates/component.js'),
fileName: 'gpt-ads-module/component.js',
options: templatesOptions,
})
}
module.exports.meta = require('../package.json')

View File

@ -1,255 +0,0 @@
/* eslint-disable no-undef */
export default {
name: '<%= options.componentName %>',
data: () => ({
adSlot: null,
mapping: [],
currentSizeMappingIndex: null,
windowResizeListenerDebounce: null,
isEmpty: true,
}),
props: {
adUnit: {
type: String,
required: true,
},
size: {
type: [Array, String],
required: true,
},
sizeMapping: {
type: Array,
required: false,
default: () => [],
},
id: {
type: [Number, String],
required: false,
default: () => Math.random().toString(36).substring(5),
},
isResponsive: {
type: Boolean,
required: false,
default: '<%= options.responsive %>' === 'true',
},
windowResizeDebounce: {
type: Number,
required: false,
default: 300,
},
collapseEmptyDiv: {
type: Boolean,
required: false,
default: null,
},
},
computed: {
ghostMode() {
return this.$config.ads.ghostMode ?? '<%= options.ghostMode %>' === true
},
networkCode() {
const { $gptAds } = this
return $gptAds ? $gptAds.networkCode : null
},
adUnitPath() {
const { networkCode, adUnit } = this
return `/${networkCode}/${adUnit}`
},
divId() {
const { id } = this
return `div-gpt-ad-${id}-0`
},
formattedSize() {
return this.formatSizeList(this.size)
},
style() {
if (this.ghostMode) {
const { formattedSize, currentSizeMappingIndex, mapping } = this
let baseSize = formattedSize
if (currentSizeMappingIndex !== null) {
baseSize = mapping[currentSizeMappingIndex][1]
}
const size = Array.isArray(baseSize[0])
? baseSize[0]
: [baseSize[0], baseSize[1]]
const [width, height] = size
return {
margin: '0 auto',
width: `${width}px`,
height: `${height}px`,
border: '1px solid black',
}
}
return null
},
},
methods: {
/**
* Formats a given size to make it compatible with GPT
* If size is an Array, it is returned as is
* If size is a string, it is formatted so that 123x456 becomes [123, 456]
*
* @param {Array,string} size The size
* @return {Array} Formatted size
*/
formatSize(size) {
if (Array.isArray(size)) {
return size
}
if (typeof size === 'string') {
return size.split('x').map((value) => parseInt(value, 10))
}
return []
},
/**
* Formats a given list of sizes to make it compatible with GPT API
* If sizesList is an Array, it is returned as is
* If sizesList is a string, it is formatted so that
* 123x456,654x321 becomes [[123, 456], [654, 321]]
*
* @param {Array,string} sizesList The sizes
* @return {Array} Formatted sizes list
*/
formatSizeList(sizesList) {
if (Array.isArray(sizesList)) {
return sizesList
}
if (typeof sizesList === 'string') {
return sizesList.split(',').map((size) => this.formatSize(size))
}
return []
},
/**
* Refresh ad slot
*/
refreshSlot() {
console.log('Refreshing slot.')
googletag.pubads().refresh([this.adSlot])
},
handleSlotRenderEnded(event) {
if (event.slot.getSlotId().getDomId() !== this.divId) {
return
}
this.isEmpty = !!event.isEmpty
},
/**
* Window resize event listener
* Attached only when responsive mode is enabled, it checks wether a different size
* mapping can be activated after resize and forces the slot to be refreshed if it's
* the case
*/
handleWindowResize() {
const { windowResizeDebounce } = this
clearTimeout(this.windowResizeListenerDebounce)
this.windowResizeListenerDebounce = setTimeout(() => {
const currentSizeMappingIndex = this.getCurrentSizeMappingIndex()
if (currentSizeMappingIndex !== this.currentSizeMappingIndex) {
if (!this.ghostMode) {
this.refreshSlot()
}
this.currentSizeMappingIndex = currentSizeMappingIndex
}
}, windowResizeDebounce)
},
/**
* Gets the current size mapping index
*
* @return {Number} The current size mapping index
*/
getCurrentSizeMappingIndex() {
const mapping = this.mapping || []
let index = null
mapping.some((size, i) => {
const [browserSize] = size
const [width, height] = browserSize
const mediaQuery = `(min-width: ${width}px) and (min-height: ${height}px)`
if (window.matchMedia(mediaQuery).matches) {
index = i
return true
}
return false
})
return index
},
},
mounted() {
if (!window.googletag) {
return
}
const { adUnitPath, divId, sizeMapping, isResponsive, collapseEmptyDiv } =
this
// Init Ad slot
googletag.cmd.push(() => {
const pubadsService = googletag.pubads()
pubadsService.addEventListener(
'slotRenderEnded',
this.handleSlotRenderEnded
)
pubadsService.setTargeting('path', this.$route.path)
const adSlot = googletag
.defineSlot(adUnitPath, this.formattedSize, divId)
.addService(pubadsService)
// Collapse empty div slot-level override
if (collapseEmptyDiv !== null) {
adSlot.setCollapseEmptyDiv(collapseEmptyDiv)
}
// Build size mapping if any
if (sizeMapping.length > 0) {
const mapping = googletag.sizeMapping()
sizeMapping.forEach((size) => {
const browserSize = this.formatSize(size[0])
const adSizes = this.formatSizeList(size[1])
mapping.addSize(browserSize, adSizes)
this.mapping.push([browserSize, adSizes])
})
adSlot.defineSizeMapping(mapping.build())
}
// Init responsive behavior
if (this.sizeMapping.length > 0 && isResponsive) {
const currentSizeMappingIndex = this.getCurrentSizeMappingIndex()
this.currentSizeMappingIndex = currentSizeMappingIndex
window.addEventListener('resize', this.handleWindowResize)
}
this.adSlot = adSlot
this.$gptAds.slots.push(adSlot)
if (!this.ghostMode) {
googletag.display(divId)
if (this.$gptAds.individualRefresh) {
this.refreshSlot()
}
}
})
},
beforeDestroy() {
console.log('Destroying ad.')
if (!googletag) {
return
}
// Destroy ad slot
googletag.cmd.push(() => {
googletag.destroySlots([this.adSlot])
})
// Remove window resize listener
window.removeEventListener('resize', this.handleWindowResize)
},
render(h) {
const { divId, style, isEmpty } = this
const classAttr = isEmpty ? '<%= options.emptyClass %>' : ''
return h('div', {
style,
attrs: {
id: divId,
class: classAttr,
},
domProps: { innerHTML: '' },
})
},
}

View File

@ -1,133 +0,0 @@
import Vue from 'vue'
function isPersonalizedAdsOn(ctx) {
let cookies = []
if (ctx.req != null) {
// Server side rendering
cookies = ctx.req.headers.cookie
} else {
// Rely on the client
cookies = document.cookie
}
if (cookies == null) return false
const processed = {}
cookies.split(';').forEach((e) => {
const val = e.trim().split('=')
processed[val[0]] = decodeURI(val[1])
})
const scopes = decodeURIComponent(processed['modrinth-scopes']).split(',')
return scopes !== null && scopes.includes('ads')
}
// eslint-disable-next-line require-await
export default async function (ctx, inject) {
const config = (ctx.$config && ctx.$config.ads) || {}
// Module options
const debug = config.debug ?? '<%= options.debug || false %>' === 'true'
const individualRefresh =
config.individualRefresh ??
'<%= options.individualRefresh || false %>' === 'true'
const collapseEmptyDivs =
config.collapseEmptyDivs ??
'<%= options.collapseEmptyDivs || false %>' === 'true'
const ethicalAds = config.ethicalAds === 'true'
const GeoEdgeId = config.GeoEdgeId ?? '<%= options.geoEdgeId %>'
const networkCode = config.networkCode ?? '<%= options.networkCode %>'
const GPT_LIB_SCRIPT_ID = '<%= options.GPT_LIB_SCRIPT_ID %>'
const GPT_INIT_SCRIPT_ID = '<%= options.GPT_INIT_SCRIPT_ID %>'
const GEOEDGE_CONF_SCRIPT_ID = '<%= options.GEOEDGE_CONF_SCRIPT_ID %>'
const GEOEDGE_LIB_SCRIPT_ID = '<%= options.GEOEDGE_LIB_SCRIPT_ID %>'
// Instance options
const gptAdsOptions = {
networkCode,
individualRefresh,
slots: [],
}
const injectScript = (script) => {
const scriptIndex = ctx.app.head.script.findIndex(
(s) => s.hid === script.hid
)
if (scriptIndex !== -1) {
ctx.app.head.script[scriptIndex] = script
} else {
ctx.app.head.script.push(script)
}
}
Vue.component('GptAd', {})
if (ethicalAds) {
return
}
const noConsent = !isPersonalizedAdsOn(ctx)
// GeoEdge support
if (GeoEdgeId !== '') {
// Unfortunately these lines are needed to prevent vue-meta from esacping quotes in the init script
ctx.app.head.__dangerouslyDisableSanitizersByTagID =
ctx.app.head.__dangerouslyDisableSanitizersByTagID || {}
ctx.app.head.__dangerouslyDisableSanitizersByTagID[GEOEDGE_CONF_SCRIPT_ID] =
['innerHTML']
const geoEdgeConfig = {
hid: GEOEDGE_CONF_SCRIPT_ID,
innerHTML:
"window.grumi = { key: '" + encodeURIComponent(GeoEdgeId) + "'};",
}
injectScript(geoEdgeConfig)
const geoEdgeImport = {
hid: GEOEDGE_LIB_SCRIPT_ID,
src: `https://rumcdn.geoedge.be/${GeoEdgeId}/grumi-ip.js`,
async: true,
}
injectScript(geoEdgeImport)
}
// Inject GPT lib
const gptLibScript = {
hid: GPT_LIB_SCRIPT_ID,
src: 'https://www.googletagservices.com/tag/js/gpt.js',
async: true,
}
injectScript(gptLibScript)
// Inject GPT init script
let gptInitScriptHtml =
'var googletag = googletag || {};googletag.cmd = googletag.cmd || [];'
if (debug) {
gptInitScriptHtml +=
'googletag.cmd.push(function(){googletag.openConsole();});'
}
// Disable initial load
const gptDisableInitialLoad = individualRefresh
? 'googletag.pubads().disableInitialLoad();'
: ''
// Collapse empty div
const gptCollapseEmptyDivs = collapseEmptyDivs
? 'googletag.pubads().collapseEmptyDivs();'
: ''
// Desactivate personalization
const gptDisablePersonalization = noConsent
? 'googletag.pubads().setRequestNonPersonalizedAds(1);'
: ''
gptInitScriptHtml += `
googletag.cmd.push(function(){
googletag.pubads().enableSingleRequest();
${gptDisableInitialLoad}
${gptCollapseEmptyDivs}
${gptDisablePersonalization}
googletag.enableServices();
});
`
const gptInitScript = {
hid: GPT_INIT_SCRIPT_ID,
innerHTML: gptInitScriptHtml,
}
injectScript(gptInitScript)
const component = require('./component.js')
Vue.component('<%= options.componentName %>', component.default || component)
inject('gptAds', gptAdsOptions)
}

View File

@ -1,35 +0,0 @@
{
"name": "@ax2/gpt-ads-module",
"version": "0.6.0",
"description": "Google Publisher Tag ads integration for Nuxt",
"license": "MIT",
"contributors": [
{
"name": "Paul Gascou-Vaillancourt <paul@ax2.ca>"
}
],
"main": "lib/module.js",
"repository": "https://github.com/ax2inc/nuxt-modules",
"homepage": "https://github.com/ax2inc/nuxt-modules/tree/master/packages/gpt-ads#readme",
"publishConfig": {
"access": "public"
},
"files": [
"lib"
],
"devDependencies": {
"codecov": "latest",
"eslint": "5.13.0",
"eslint-config-airbnb-base": "13.1.0",
"eslint-loader": "2.1.2",
"eslint-plugin-import": "2.16.0",
"eslint-plugin-jest": "22.3.0",
"eslint-plugin-vue": "5.2.1",
"jest": "24.1.0",
"jsdom": "14.0.0",
"nuxt": "2.4.3",
"request-promise-native": "1.0.5",
"standard-version": "latest"
},
"gitHead": "db930bf38f5eec5696ad7978a68656436831fc59"
}

View File

@ -202,9 +202,6 @@ export default {
'@nuxtjs/style-resources', '@nuxtjs/style-resources',
'@nuxtjs/markdownit', '@nuxtjs/markdownit',
'cookie-universal-nuxt', 'cookie-universal-nuxt',
'~/modules/gpt-ads',
// The analytics module is disabled, as we are using our own solution embedded in the middleware.
// '~/modules/analytics',
], ],
ads: { ads: {
// Module options // Module options
@ -286,9 +283,6 @@ export default {
browserBaseURL: process.env.BROWSER_BASE_URL, browserBaseURL: process.env.BROWSER_BASE_URL,
}, },
ads: { ads: {
ghostMode: process.env.ENABLE_ADS == null,
GeoEdgeId: process.env.GEOEDGE_ID,
networkCode: process.env.GAM_ID,
ethicalAds: process.env.ETHICAL_ADS, ethicalAds: process.env.ETHICAL_ADS,
}, },
analytics: { analytics: {