From 4aac580cd6b8d44f6f67131b3cbeea5a96f080a4 Mon Sep 17 00:00:00 2001 From: milanmajchrak Date: Wed, 25 Nov 2026 18:48:32 +0100 Subject: [PATCH] CLARIN-DSpace v9/Load Matomo only after cookie consent Ports dtq-dev 7eddad8db7 (Matomo only after consent, no replay of declined activity). Co-Authored-By: Claude Opus 5.5 --- src/app/statistics/matomo.service.spec.ts | 220 +++++++++++++++++++--- src/app/statistics/matomo.service.ts | 90 +++++++-- src/modules/app/browser-app.config.ts | 3 +- 3 files changed, 267 insertions(+), 46 deletions(-) diff --git a/src/app/statistics/matomo.service.spec.ts b/src/app/statistics/matomo.service.spec.ts index 162fb483ea8..e5f79ce144b 100644 --- a/src/app/statistics/matomo.service.spec.ts +++ b/src/app/statistics/matomo.service.spec.ts @@ -9,7 +9,10 @@ import { MatomoTracker, } from 'ngx-matomo-client'; import { MatomoTestingModule } from 'ngx-matomo-client/testing'; -import { of } from 'rxjs'; +import { + firstValueFrom, + of, +} from 'rxjs'; import { environment } from '../../environments/environment'; import { ConfigurationDataService } from '../core/data/configuration-data.service'; @@ -27,6 +30,7 @@ import { MATOMO_ENABLED, MATOMO_SITE_ID, MATOMO_TRACKER_URL, + matomoConsentInterceptor, matomoItemDimensionInterceptor, MatomoService, } from './matomo.service'; @@ -38,12 +42,20 @@ describe('MatomoService', () => { let orejimeService: jasmine.SpyObj; let nativeWindowService: jasmine.SpyObj; let configService: jasmine.SpyObj; + let paq: any[]; beforeEach(() => { - matomoTracker = jasmine.createSpyObj('MatomoTracker', ['setConsentGiven', 'forgetConsentGiven', 'getVisitorId', 'setCustomDimension', 'deleteCustomDimension']); + paq = []; + matomoTracker = jasmine.createSpyObj('MatomoTracker', ['setConsentGiven', 'forgetConsentGiven', 'getVisitorId', 'setCustomDimension', 'deleteCustomDimension', 'setCustomRequestProcessing', 'trackPageView']); + // like ngx-matomo, the tracker queues its commands for matomo.js + matomoTracker.setConsentGiven.and.callFake(() => paq.push(['setConsentGiven'])); + matomoTracker.forgetConsentGiven.and.callFake(() => paq.push(['forgetConsentGiven'])); + matomoTracker.setCustomRequestProcessing.and.callFake((processor) => paq.push(['setCustomRequestProcessing', processor])); + matomoTracker.trackPageView.and.callFake(() => paq.push(['trackPageView'])); matomoInitializer = jasmine.createSpyObj('MatomoInitializerService', ['initializeTracker', 'initialize']); orejimeService = jasmine.createSpyObj('OrejimeService', ['getSavedPreferences']); - nativeWindowService = jasmine.createSpyObj('NativeWindowService', [], { nativeWindow: {} }); + orejimeService.getSavedPreferences.and.returnValue(of(undefined)); + nativeWindowService = jasmine.createSpyObj('NativeWindowService', [], { nativeWindow: { _paq: paq } }); configService = jasmine.createSpyObj('ConfigurationDataService', ['findByPropertyName']); configService.findByPropertyName.and.returnValue(createFailedRemoteDataObject$()); @@ -72,18 +84,6 @@ describe('MatomoService', () => { expect(nativeWindowService.nativeWindow.changeMatomoConsent).toBe(service.changeMatomoConsent); }); - it('should call setConsentGiven when consent is true', () => { - service.matomoTracker = matomoTracker; - service.changeMatomoConsent(true); - expect(matomoTracker.setConsentGiven).toHaveBeenCalled(); - }); - - it('should call forgetConsentGiven when consent is false', () => { - service.matomoTracker = matomoTracker; - service.changeMatomoConsent(false); - expect(matomoTracker.forgetConsentGiven).toHaveBeenCalled(); - }); - it('should initialize tracker with values from angular configuration', () => { environment.production = true; environment.matomo = { trackerUrl: 'http://localhost:80801' }; @@ -99,7 +99,6 @@ describe('MatomoService', () => { service.init(); - expect(matomoTracker.setConsentGiven).toHaveBeenCalled(); expect(matomoInitializer.initializeTracker).toHaveBeenCalledWith({ siteId: '1', trackerUrl: 'http://localhost:80801', @@ -123,7 +122,6 @@ describe('MatomoService', () => { tick(); - expect(matomoTracker.setConsentGiven).toHaveBeenCalled(); expect(matomoInitializer.initializeTracker).toHaveBeenCalledWith({ siteId: '1', trackerUrl: 'http://example.com', @@ -156,6 +154,180 @@ describe('MatomoService', () => { expect(matomoInitializer.initializeTracker).not.toHaveBeenCalled(); }); + describe('consent', () => { + const trackerUrl = 'https://matomo.example.org/'; + let sent: string[]; + let consentCalls: string[]; + let runQueue: () => void; + let previousEnvironment; + + const consent = (given: boolean) => nativeWindowService.nativeWindow.changeMatomoConsent(given); + + // The router's commands for one page view: url, interceptors, page view + const routerPageView = (url: string) => { + paq.push(['setCustomUrl', url]); + TestBed.runInInjectionContext(() => matomoConsentInterceptor()); + paq.push(['trackPageView']); + }; + + // Runs the commands not run yet, like matomo.js: on load it runs the queued consent names first, requests go + // through the request processor, and Matomo holds them while consent is required and sends the held ones on + // setConsentGiven, skipping empty ones + const createMatomo = () => { + let processor = (request: string) => request; + let url: string; + let held: string[]; + const send = (request: string) => request && sent.push(request); + const requireConsent = () => held = held ?? []; + const matomo = { + setCustomRequestProcessing: (fn) => processor = fn, + setCustomUrl: (value) => url = value, + trackPageView: () => held ? held.push(processor(`url=${url}`)) : send(processor(`url=${url}`)), + requireConsent, + forgetConsentGiven: () => { + consentCalls.push('forgetConsentGiven'); + requireConsent(); + }, + setConsentGiven: () => { + consentCalls.push('setConsentGiven'); + held?.forEach(send); + held = undefined; + }, + }; + const runFirstOnLoad = ['requireConsent', 'setConsentGiven']; + const run = ([command, ...args]) => typeof command === 'function' ? command.apply(matomo, args) : matomo[command]?.(...args); + let next = 0; + let loaded = false; + return () => { + let commands = paq.slice(next); + next = paq.length; + if (!loaded) { + loaded = true; + commands = [ + ...commands.filter(([command]) => runFirstOnLoad.includes(command)), + ...commands.filter(([command]) => !runFirstOnLoad.includes(command)), + ]; + } + commands.forEach(run); + }; + }; + + const configureMatomo = (enabled = 'true', siteId = '1') => { + configService.findByPropertyName.withArgs(MATOMO_ENABLED).and.returnValue( + createSuccessfulRemoteDataObject$(Object.assign(new ConfigurationProperty(), { values: [enabled] }))); + configService.findByPropertyName.withArgs(MATOMO_SITE_ID).and.returnValue( + createSuccessfulRemoteDataObject$(Object.assign(new ConfigurationProperty(), { values: [siteId] }))); + }; + + beforeEach(() => { + previousEnvironment = { production: environment.production, matomo: environment.matomo, info: environment.info }; + environment.production = true; + environment.matomo = { trackerUrl }; + environment.info = { ...environment.info, enableCookieConsentPopup: true }; + sent = []; + consentCalls = []; + runQueue = createMatomo(); + configureMatomo(); + }); + + afterEach(() => { + Object.assign(environment, previousEnvironment); + }); + + it('should load Matomo and track the current page only once the visitor consents', () => { + service.init(); + routerPageView('/items/before-consent'); + routerPageView('/items/current'); + consent(false); + + expect(matomoInitializer.initializeTracker).not.toHaveBeenCalled(); + + consent(true); + runQueue(); + + expect(matomoInitializer.initializeTracker).toHaveBeenCalledOnceWith({ siteId: '1', trackerUrl }); + expect(sent).toEqual(['url=/items/current']); + }); + + it('should stop tracking on revocation and never send activity from the declined period', () => { + orejimeService.getSavedPreferences.and.returnValue(of({ matomo: true })); + service.init(); + routerPageView('/accepted'); + runQueue(); + + consent(false); + routerPageView('/declined'); + routerPageView('/current'); + runQueue(); + + expect(sent).toEqual(['url=/accepted']); + expect(consentCalls).toEqual(['setConsentGiven', 'forgetConsentGiven']); + + consent(true); + routerPageView('/next'); + runQueue(); + + expect(sent).toEqual(['url=/accepted', 'url=/current', 'url=/next']); + expect(matomoInitializer.initializeTracker).toHaveBeenCalledTimes(1); + }); + + it('should keep consent changes in order when they happen before Matomo has loaded', () => { + service.init(); + routerPageView('/landing'); + consent(true); + consent(false); + routerPageView('/declined'); + routerPageView('/current'); + consent(true); + runQueue(); + + expect(sent).toEqual(['url=/landing', 'url=/current']); + }); + + it('should not load Matomo without a tracker URL and site ID', () => { + [['false', '1'], ['true', '']].forEach(([enabled, siteId]) => { + configureMatomo(enabled, siteId); + service.init(); + consent(true); + }); + environment.matomo = { trackerUrl: '' }; + configService.findByPropertyName.withArgs(MATOMO_TRACKER_URL).and.returnValue(createFailedRemoteDataObject$()); + configureMatomo(); + service.init(); + consent(true); + + expect(matomoInitializer.initializeTracker).not.toHaveBeenCalled(); + expect(matomoTracker.trackPageView).not.toHaveBeenCalled(); + }); + + it('should track without consent when the consent popup is disabled', () => { + environment.info = { ...environment.info, enableCookieConsentPopup: false }; + orejimeService.getSavedPreferences.and.returnValue(of({ matomo: false })); + service.init(); + routerPageView('/items/current'); + runQueue(); + + expect(matomoInitializer.initializeTracker).toHaveBeenCalled(); + expect(sent).toEqual(['url=/items/current']); + }); + + it('should add the visitor id to a download link only while the visitor consents', async () => { + const url = 'http://example.com/'; + matomoTracker.getVisitorId.and.returnValue(Promise.resolve('12345')); + service.init(); + + expect(await firstValueFrom(service.appendVisitorId(url))).toBe(url); + + consent(true); + + expect(await firstValueFrom(service.appendVisitorId(url))).toBe('http://example.com/?trackerId=12345'); + + consent(false); + + expect(await firstValueFrom(service.appendVisitorId(url))).toBe(url); + }); + }); + describe('per-item custom dimension', () => { const handle = 'https://hdl.handle.net/123456789/1'; let previousMatomoConfig; @@ -222,18 +394,4 @@ describe('MatomoService', () => { }); }); - describe('with visitorId set', () => { - beforeEach(() => { - matomoTracker.getVisitorId.and.returnValue(Promise.resolve('12345')); - service.matomoTracker = matomoTracker; - }); - - it('should add trackerId parameter', fakeAsync(() => { - service.appendVisitorId('http://example.com/') - .subscribe(url => expect(url).toEqual('http://example.com/?trackerId=12345')); - tick(); - })); - - }); - }); diff --git a/src/app/statistics/matomo.service.ts b/src/app/statistics/matomo.service.ts index ad657bf1674..3e586fd46ec 100644 --- a/src/app/statistics/matomo.service.ts +++ b/src/app/statistics/matomo.service.ts @@ -64,6 +64,20 @@ export class MatomoService { /** Handle of the item whose page view is about to be tracked, when the current page has one. */ private itemHandle: string; + /** Whether the visitor's consent to Matomo is applied. */ + private consent = false; + + /** The consent in force at the point Matomo has reached in its command queue. */ + private consentInQueue = false; + + /** Whether the router queued the current page view without consent. */ + private pageViewWithoutConsent = false; + + /** Site id and tracker URL, once Matomo is enabled and configured. */ + private trackerConfig: { siteId: string, trackerUrl: string }; + + private scriptInjected = false; + private statusSubject = new ReplaySubject<'loading' | 'loaded' | 'error'>(1); private status$ = this.statusSubject.asObservable(); @@ -88,7 +102,7 @@ export class MatomoService { /** * Initializes the Matomo tracker if in production environment. * Sets up the changeMatomoConsent function on the native window object. - * Subscribes to cookie consent preferences and initializes the tracker accordingly. + * Subscribes to cookie consent preferences and applies them once Matomo is configured. */ init() { if (this._window.nativeWindow) { @@ -96,40 +110,71 @@ export class MatomoService { } if (environment.production) { + this.matomoTracker = runInInjectionContext(this.injector, () => inject(MatomoTracker)); + // Set before the router queues its first page view. Matomo then empties, and never sends, every request + // queued without consent, even when it runs the queue after a later consent. + this.matomoTracker.setCustomRequestProcessing((request: string) => this.consentInQueue ? request : ''); + const preferences$ = this.orejimeService.getSavedPreferences(); combineLatest([preferences$, this.isMatomoEnabled$(), this.getSiteId$(), this.getTrackerUrl$()]) .subscribe(([preferences, isMatomoEnabled, siteId, trackerUrl]) => { if (isMatomoEnabled && siteId && trackerUrl) { - runInInjectionContext(this.injector, () => { - this.matomoTracker = inject(MatomoTracker); - this.matomoInitializer = inject(MatomoInitializerService); - }); - this.matomoInitializer.initializeTracker({ siteId, trackerUrl }); - this.changeMatomoConsent(preferences?.matomo); + this.matomoInitializer = runInInjectionContext(this.injector, () => inject(MatomoInitializerService)); + this.trackerConfig = { siteId, trackerUrl }; + this.changeMatomoConsent(environment.info?.enableCookieConsentPopup === false || preferences?.matomo); } }); } } /** - * Changes the Matomo consent status based on the given consent value. + * Applies the visitor's Matomo consent once Matomo is configured. The first consent loads the Matomo script. + * A consent tracks the current page if the router queued it without consent. A revocation stops tracking, + * and Matomo deletes its cookies. * @param consent - A boolean indicating whether consent is given for Matomo tracking. */ changeMatomoConsent = (consent: boolean) => { - if (consent) { - this.matomoTracker?.setConsentGiven(); - } else { - this.matomoTracker?.forgetConsentGiven(); + const given = !!consent; + if (!this.trackerConfig || given === this.consent) { + return; + } + this.consent = given; + if (given && !this.scriptInjected) { + this.scriptInjected = true; + this.matomoInitializer.initializeTracker(this.trackerConfig); + } + this.runInQueue((matomo) => { + this.consentInQueue = given; + if (given) { + matomo.setConsentGiven(); + } else { + matomo.forgetConsentGiven(); + } + }); + if (given && this.pageViewWithoutConsent) { + this.pageViewWithoutConsent = false; + this.matomoTracker.trackPageView(); } }; /** - * Appends the Matomo visitor ID to the given URL. + * Remembers whether the router queues the coming page view without consent, so that page is tracked once + * consent is given. + */ + notePageView() { + this.pageViewWithoutConsent = !this.consent; + } + + /** + * Appends the Matomo visitor ID to the given URL, while the visitor consents to Matomo. * @param url - The original URL to which the visitor ID will be added. - * @returns An Observable that emits the URL with the visitor ID appended. + * @returns An Observable that emits the URL with the visitor ID appended, or the URL unchanged without consent. */ appendVisitorId(url: string): Observable { + if (!this.consent) { + return of(url); + } return fromPromise(this.matomoTracker?.getVisitorId()) .pipe( map(visitorId => this.appendTrackerId(url, visitorId)), @@ -238,6 +283,16 @@ export class MatomoService { } return updatedURL.toString(); } + + /** + * Runs fn on the Matomo tracker when Matomo reaches it in its command queue. Matomo would run a queued + * 'setConsentGiven' name before the commands queued ahead of it, so consent changes go through here. + */ + private runInQueue(fn: (matomo: any) => void) { + this._window.nativeWindow._paq.push([function () { + fn(this); + }]); + } } /** @@ -246,3 +301,10 @@ export class MatomoService { export function matomoItemDimensionInterceptor(): void { inject(MatomoService).applyItemCustomDimension(); } + +/** + * Matomo router interceptor that notes whether the coming page view is queued without consent. + */ +export function matomoConsentInterceptor(): void { + inject(MatomoService).notePageView(); +} diff --git a/src/modules/app/browser-app.config.ts b/src/modules/app/browser-app.config.ts index 8743a596372..0173eb9eb24 100644 --- a/src/modules/app/browser-app.config.ts +++ b/src/modules/app/browser-app.config.ts @@ -41,6 +41,7 @@ import { } from 'ngx-matomo-client'; import { customMatomoScriptFactory } from 'src/app/statistics/matomo.factory'; import { + matomoConsentInterceptor, matomoItemDimensionInterceptor, MatomoService, } from 'src/app/statistics/matomo.service'; @@ -175,7 +176,7 @@ export const browserAppConfig: ApplicationConfig = mergeApplicationConfig({ }, withRouter(), withRouteData(), - withRouterInterceptors([matomoItemDimensionInterceptor]), + withRouterInterceptors([matomoItemDimensionInterceptor, matomoConsentInterceptor]), ), { provide: MATOMO_SCRIPT_FACTORY,