Change ads provider, and add consent system for advertising (#155)

* Add GAM integration & base for GPDR consent

* Moved consent to a specific page.

* Added functionality to the privacy page, and desactivate tracking if consent is not given.

* Added GeoEdge support, and fixed auth issues

* Fix actions issue

* Fix actions issue, attempt 2

* Added a module for analytics with consent support.

* Remove unnecessary function

* Add support for runtime config
This commit is contained in:
Redblueflame
2021-04-09 04:44:25 +02:00
committed by GitHub
parent 103ce44ba9
commit 03b2d02742
29 changed files with 1729 additions and 46 deletions

View File

@@ -0,0 +1,6 @@
export const DEFAULT_OPTIONS = {
enabled: false,
script_url: 'https://example.com',
tracking_code: 'xxx'
}
export const UNAMI_LIB_TAG_ID = 'unami-import'

View File

@@ -0,0 +1,22 @@
import {
DEFAULT_OPTIONS,
UNAMI_LIB_TAG_ID
} from './constants';
const { resolve } = require('path');
module.exports = async function module(moduleOptions) {
const options = Object.assign(DEFAULT_OPTIONS, this.options.analytics, moduleOptions);
const templatesOptions = {
...options,
UNAMI_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

@@ -0,0 +1,64 @@
import Vue from 'vue';
function isAnalyticsOn(ctx) {
let cookies = null
if (ctx.req != null) {
//Server side rendering
cookies = ctx.req.headers.cookie;
} else {
// Rely on the client
cookies = document.cookie;
}
let processed = {}
cookies.split(';').forEach((e) => {
let val = e.trim().split('=');
processed[val[0]] = decodeURI(val[1]);
})
let scopes = decodeURIComponent(processed['modrinth-scopes']).split(",");
return (scopes !== null && scopes.includes('analytics'));
}
export default async function (ctx, inject) {
const { app } = ctx;
const config = ctx.$config && ctx.$config.analytics || {};
const url = config.script_url ?? '<%= options.script_url %>';
const tag = config.tracking_code ?? '<%= options.tracking_code %>';
const enabled = config.enabled ?? <%= options.enabled || false %>;
// Check if the parameters are not changed by runtime config:
const UNAMI_LIB_TAG_ID = '<%= options.UNAMI_LIB_TAG_ID %>';
if (!enabled) {
console.log("Analytics are not 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);
}
};
if (isAnalyticsOn(ctx)) {
// Inject unami
const analyticsScript = {
hid: UNAMI_LIB_TAG_ID,
src: url,
'data-website-id': 'c37613de-245d-4767-90e7-ba7980a4f1a2',
async: true,
defer: true,
};
injectScript(analyticsScript);
} else {
// console.log("Analytics scope was denied.")
}
}

View File

@@ -0,0 +1,31 @@
{
"name": "@modrinth/analytics",
"version": "0.1.0",
"description": "Unami 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

@@ -0,0 +1,16 @@
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

@@ -0,0 +1,34 @@
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');
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

@@ -0,0 +1,256 @@
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 %>,
},
windowResizeDebounce: {
type: Number,
required: false,
default: 300,
},
collapseEmptyDiv: {
type: Boolean,
required: false,
default: null,
},
},
computed: {
ghostMode() {
return this.$config.ads.ghostMode ?? <%= options.ghostMode %>;
},
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() {
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 {
ghostMode,
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() {
if (!googletag) {
return;
}
// Destroy ad slot
googletag.cmd.push(() => {
const destroyed = googletag.destroySlots([this.adSlot]);
});
// Remove window resize listener
window.removeEventListener('resize', this.handleWindowResize);
},
render(h) {
const { divId, style, isEmpty } = this;
let classAttr = isEmpty ? '<%= options.emptyClass %>' : '';
return h('div', {
style,
attrs: {
id: divId,
class: classAttr,
},
domProps: { innerHTML: '' },
});
},
};

View File

@@ -0,0 +1,111 @@
import Vue from 'vue';
function isPersonalizedAdsOn(ctx) {
let cookies = null
if (ctx.req != null) {
//Server side rendering
cookies = ctx.req.headers.cookie;
} else {
// Rely on the client
cookies = document.cookie;
}
let processed = {}
cookies.split(';').forEach((e) => {
let val = e.trim().split('=')
processed[val[0]] = decodeURI(val[1])
})
let scopes = decodeURIComponent(processed['modrinth-scopes']).split(",")
return (scopes !== null && scopes.includes('ads'))
}
export default async function (ctx, inject) {
const { app } = ctx;
const config = ctx.$config && ctx.$config.ads || {};
// Module options
const debug = config.debug ?? <%= options.debug || false %>;
const individualRefresh = config.individualRefresh ?? <%= options.individualRefresh || false %>;
const collapseEmptyDivs = config.collapseEmptyDivs ?? <%= options.collapseEmptyDivs || false %>;
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);
}
};
let no_consent = !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 = no_consent ? '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

@@ -0,0 +1,35 @@
{
"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"
}