-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathmatomo.dart
More file actions
1053 lines (946 loc) · 31.5 KB
/
Copy pathmatomo.dart
File metadata and controls
1053 lines (946 loc) · 31.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import 'dart:async';
import 'dart:collection';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:matomo_tracker/src/assert.dart';
import 'package:matomo_tracker/src/campaign.dart';
import 'package:matomo_tracker/src/content.dart';
import 'package:matomo_tracker/src/dispatch_settings.dart';
import 'package:matomo_tracker/src/event_info.dart';
import 'package:matomo_tracker/src/exceptions.dart';
import 'package:matomo_tracker/src/local_storage/cookieless_storage.dart';
import 'package:matomo_tracker/src/local_storage/local_storage.dart';
import 'package:matomo_tracker/src/local_storage/shared_prefs_storage.dart';
import 'package:matomo_tracker/src/logger/log_record.dart';
import 'package:matomo_tracker/src/logger/logger.dart';
import 'package:matomo_tracker/src/matomo_action.dart';
import 'package:matomo_tracker/src/matomo_dispatcher.dart';
import 'package:matomo_tracker/src/performance_info.dart';
import 'package:matomo_tracker/src/persistent_queue.dart';
import 'package:matomo_tracker/src/platform_info/platform_info.dart';
import 'package:matomo_tracker/src/tracking_order_item.dart';
import 'package:matomo_tracker/src/visitor.dart';
import 'package:matomo_tracker/utils/lock.dart' as sync;
import 'package:matomo_tracker/utils/random_alpha_numeric.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:uuid/uuid.dart';
/// Implementation of the Matomo [Tracking HTTP API](https://developer.matomo.org/api-reference/tracking-api).
///
/// If this documentation refers to a correspondence with a parameter, check out
/// the [Tracking HTTP API](https://developer.matomo.org/api-reference/tracking-api)
/// documentation for more information on that parameter.
class MatomoTracker {
/// This is only used for testing purpose, because testing singleton is hard.
@visibleForTesting
MatomoTracker();
MatomoTracker._internal();
final log = Logger('Matomo');
late final PlatformInfo _platformInfo;
@visibleForTesting
MatomoDispatcher get dispatcher => _dispatcher;
late MatomoDispatcher _dispatcher;
static final instance = MatomoTracker._internal();
/// The ID of the website we're tracking a visit/action for.
///
/// Corresponds with `idsite`.
late final String siteId;
/// The url of the Matomo endpoint.
///
/// E.g.: `https://example.com/matomo.php`
///
/// Should not be confused with the `url` tracking parameter
/// which is constructed by combining [contentBase] with a `path`
/// (e.g. in [trackPageViewWithName]).
///
/// You can use [setUrl] to change this value after initialization.
String get url {
if (_url case final url?) {
return url;
}
throw const UninitializedMatomoInstanceException();
}
String? _url;
/// Sets the url of the Matomo endpoint and updates the dispatcher.
///
/// Note that this will change the url used by the request that are still
/// in the queue.
void setUrl(String newUrl) {
_initializationCheck();
_url = newUrl;
_dispatcher = _dispatcher.copyWith(baseUrl: newUrl);
}
Visitor get visitor => _visitor;
late Visitor _visitor;
/// The Matomo request parameter used for [visitor.id].
///
/// This defaults to [VisitorIdParameter.id], which sends the ID as `_id`.
/// Set it to [VisitorIdParameter.cid] during [initialize] only when the
/// application has a stable, valid Matomo visitor ID and needs to explicitly
/// control Matomo's visitor matching for each request.
late final VisitorIdParameter visitorIdParameter;
/// Sets the [User ID](https://matomo.org/guide/reports/user-ids/).
///
/// This should not be confused with the [visitorId] of the [initialize]
/// call (which corresponds with the `_id` parameter).
void setVisitorUserId(String? uid) {
_initializationCheck();
_visitor = Visitor(
id: _visitor.id,
uid: uid,
);
}
/// The active locale (language & country code) for the current user.
/// Set this to override the language reported the system-reported default locale of the device.
/// Attention: Changing the user locale might override visitor country if GeoIP is not enabled.
/// If you don't want this behavior, consider saving the user locale as a custom dimension:
/// https://matomo.org/guide/reporting-tools/custom-dimensions/
Locale? userLocale;
/// Whether to attach `pvId` and `path` to `track...` calls automatically.
///
/// There most actions can be associated with page views by setting a `pvId`
/// (what is the abbreviation of page view id). If [attachLastScreenInfo] is
/// `true` and there is a last page view tracked by [trackPageViewWithName] (or
/// a method/class that uses it like [trackPageView], [TraceableClientMixin],
/// [TraceableWidget]) the last recorded `pvId` is automatically used unless
/// it is overwritten in that action.
///
/// Similarly, most actions can have a `path` which usually represents the page
/// the action happend on. If [attachLastScreenInfo] is `true` and there is a
/// last page view tracked by a method mentioned above, the last recorded `path`
/// is automatically used unless it is overwritten in that action.
late final bool attachLastScreenInfo;
/// The user agent is used to detect the operating system and browser used.
late final String? userAgent;
/// Custom http headers to add to each request.
late final Map<String, String> customHeaders;
/// URL for the current action.
///
/// For the tracking of screens (e.g. with [trackPageViewWithName]) this is combined
/// with the `path` parameter to create the tracked `url`.
late final String contentBase;
/// The resolution of the device the visitor is using, eg **1280x1024**.
late final Size screenResolution;
bool _initialized = false;
bool get initialized => _initialized;
bool _optOut = false;
bool get optOut => _optOut;
Future<void> setOptOut({required bool optOut}) async {
_optOut = optOut;
await _localStorage.setOptOut(optOut: optOut);
}
bool _cookieless = false;
bool get cookieless => _cookieless;
Future<void> setCookieless({
required bool cookieless,
LocalStorage? localStorage,
}) async {
if (_cookieless == cookieless) return;
_cookieless = cookieless;
_setLocalStorage(localStorage);
if (cookieless) {
_visitor = const Visitor();
} else {
final visitorId = await _getVisitorId();
_validateVisitorIdParameter(
visitorId: visitorId,
visitorIdParameter: visitorIdParameter,
);
_visitor = Visitor(id: visitorId);
}
}
void _setLocalStorage(LocalStorage? localStorage) {
final effectiveLocalStorage = localStorage ?? SharedPrefsStorage();
_localStorage = cookieless
? CookielessStorage(storage: effectiveLocalStorage)
: effectiveLocalStorage;
}
late LocalStorage _localStorage;
@visibleForTesting
late final Queue<Map<String, String>> queue;
@visibleForTesting
late Timer dequeueTimer;
@visibleForTesting
Timer? pingTimer;
late sync.Lock _lock;
String? _tokenAuth;
String? get authToken => _tokenAuth;
/// Controls how actions are dispatched.
late final DispatchSettings _dispatchSettings;
late final Duration? _pingInterval;
late bool _newVisit;
MatomoAction? _lastPageView;
/// Initialize the tracker.
///
/// This method must be called before any other method. Otherwise they might
/// throw an [UninitializedMatomoInstanceException].
///
/// If the tracker is already initialized, an
/// [AlreadyInitializedMatomoInstanceException] will be thrown.
///
/// The [newVisit] parameter is used to mark this initialization the start
/// of a new visit. If set to `false` it is left to Matomo to decide if this
/// is a new visit or not. In practice, this will be used as the `newVisit`
/// parameter in the first `track...` method call but only if the `newVisit`
/// parameter in that method call is left to `null`.
///
/// The [visitorId] should have a length of 16 characters otherwise an
/// [ArgumentError] will be thrown. This parameter corresponds with the
/// `_id` by default and should not be confused with the user id `uid`. See
/// the [Visitor] class for additional remarks. It is recommended to leave
/// this to `null` to use an automatically generated id.
///
/// Set [visitorIdParameter] to [VisitorIdParameter.cid] to send the visitor
/// ID as Matomo's `cid` parameter instead. In that mode, the effective
/// visitor ID must be exactly 16 hexadecimal characters. The default is
/// [VisitorIdParameter.id], preserving the package's existing behavior.
///
/// If [cookieless] is set to true, a [CookielessStorage] instance will be
/// used. This means that the first_visit and the user_id will be stored in
/// memory and will be lost when the app is closed.
///
/// The [pingInterval] is used to set the interval in which pings are
/// send to Matomo to circumvent the [last page viewtime issue](https://github.com/Floating-Dartists/matomo-tracker/issues/78).
/// To deactivate pings, set this to `null`. The default value is a good
/// compromise between accuracy and network traffic.
///
/// It is recommended to leave [userAgent] to `null` so it will be detected
/// automatically.
Future<void> initialize({
required String siteId,
required String url,
bool newVisit = true,
String? visitorId,
VisitorIdParameter visitorIdParameter = VisitorIdParameter.id,
String? uid,
String? contentBaseUrl,
DispatchSettings dispatchSettings = const DispatchSettings.nonPersistent(),
Duration? pingInterval = const Duration(seconds: 30),
String? tokenAuth,
http.Client? httpClient,
LocalStorage? localStorage,
PackageInfo? packageInfo,
PlatformInfo? platformInfo,
bool cookieless = false,
Level verbosityLevel = Level.off,
Map<String, String> customHeaders = const {},
String? userAgent,
bool attachLastScreenInfo = true,
bool optOut = false,
}) async {
if (_initialized) {
throw const AlreadyInitializedMatomoInstanceException();
}
if (visitorId != null && visitorId.length != 16) {
throw ArgumentError.value(
visitorId,
'visitorId',
'The visitorId must be 16 characters long',
);
}
_validateVisitorIdParameter(
visitorId: visitorId,
visitorIdParameter: visitorIdParameter,
);
assertDurationNotNegative(
value: dispatchSettings.dequeueInterval,
name: 'dequeueInterval',
);
assertDurationNotNegative(
value: pingInterval,
name: 'pingInterval',
);
log.setLogging(level: verbosityLevel);
this.siteId = siteId;
_url = url;
this.customHeaders = customHeaders;
_pingInterval = pingInterval;
_lock = sync.Lock();
_platformInfo = platformInfo ?? PlatformInfo.instance;
_cookieless = cookieless;
_tokenAuth = tokenAuth;
_newVisit = newVisit;
this.attachLastScreenInfo = attachLastScreenInfo;
this.visitorIdParameter = visitorIdParameter;
_dispatchSettings = dispatchSettings;
_setLocalStorage(localStorage);
final onLoad = _dispatchSettings.onLoad;
queue = _dispatchSettings.persistentQueue && onLoad != null
? await PersistentQueue.load(
storage: _localStorage,
onLoadFilter: onLoad,
)
: Queue();
final localVisitorId = visitorId ?? await _getVisitorId();
_validateVisitorIdParameter(
visitorId: localVisitorId,
visitorIdParameter: visitorIdParameter,
);
_visitor = Visitor(id: localVisitorId, uid: uid);
// User agent
this.userAgent = userAgent ?? await getUserAgent();
_dispatcher = MatomoDispatcher(
baseUrl: url,
tokenAuth: tokenAuth,
userAgent: this.userAgent,
httpClient: httpClient,
log: log,
);
// Screen Resolution
final physicalSize = PlatformDispatcher.instance.views.first.physicalSize;
screenResolution = Size(
physicalSize.width,
physicalSize.height,
);
if (localVisitorId != null) {
// Save the visitorId for future visits.
unawaited(_saveVisitorId(localVisitorId));
}
if (contentBaseUrl != null) {
contentBase = contentBaseUrl;
} else if (kIsWeb) {
contentBase = Uri.base.toString();
} else {
final effectivePackageInfo =
packageInfo ?? await PackageInfo.fromPlatform();
contentBase = 'https://${effectivePackageInfo.packageName}';
}
_optOut = (await _localStorage.getOptOut()) ?? optOut;
unawaited(_localStorage.setOptOut(optOut: _optOut));
log.fine(
'Matomo Initialized: visitorId=$visitorId; contentBase=$contentBase; resolution=${screenResolution.width}x${screenResolution.height}; userAgent=${this.userAgent}',
);
_initialized = true;
dequeueTimer = Timer.periodic(_dispatchSettings.dequeueInterval, (_) {
_dequeue();
});
if (pingInterval != null) {
pingTimer = Timer.periodic(pingInterval, (_) {
_ping();
});
}
if (queue.isNotEmpty) {
unawaited(dispatchActions());
}
}
@visibleForTesting
Future<String?> getUserAgent({
DeviceInfoPlugin? deviceInfoPlugin,
}) async {
try {
final effectiveDeviceInfo = deviceInfoPlugin ?? DeviceInfoPlugin();
if (_platformInfo.isWeb) {
final webBrowserInfo = await effectiveDeviceInfo.webBrowserInfo;
return webBrowserInfo.userAgent;
} else if (_platformInfo.isAndroid) {
final androidInfo = await effectiveDeviceInfo.androidInfo;
final release = androidInfo.version.release;
final sdkInt = androidInfo.version.sdkInt;
final manufacturer = androidInfo.manufacturer;
final model = androidInfo.model;
return 'Android $release (SDK $sdkInt), $manufacturer $model';
} else if (_platformInfo.isIOS) {
final iosInfo = await effectiveDeviceInfo.iosInfo;
final systemName = iosInfo.systemName;
final version = iosInfo.systemVersion;
final model = iosInfo.model;
final machine = iosInfo.utsname.machine;
return '$systemName $version, $model $machine';
} else if (_platformInfo.isWindows) {
final windowsInfo = await effectiveDeviceInfo.windowsInfo;
final releaseId = windowsInfo.releaseId;
final buildNumber = windowsInfo.buildNumber;
return 'Windows $releaseId.$buildNumber';
} else if (_platformInfo.isMacOS) {
final macInfo = await effectiveDeviceInfo.macOsInfo;
final model = macInfo.model;
final version = macInfo.kernelVersion;
final release = macInfo.osRelease;
return '$model, $version, $release';
} else if (_platformInfo.isLinux) {
final linuxInfo = await effectiveDeviceInfo.linuxInfo;
return linuxInfo.prettyName;
} else {
return 'Unknown';
}
} catch (e) {
return 'Unknown';
}
}
/// {@macro local_storage.clear}
void clear() => _localStorage.clear();
/// Cancel the timer which checks the queued actions to send
///
/// This will not clear the queue.
void dispose() {
pingTimer?.cancel();
dequeueTimer.cancel();
log.clearListeners();
}
// Pause tracker
void pause() {
pingTimer?.cancel();
_ping();
dequeueTimer.cancel();
_dequeue();
}
// Resume tracker
void resume() {
final pingInterval = _pingInterval;
if (pingInterval != null) {
if (!(pingTimer?.isActive ?? false)) {
pingTimer = Timer.periodic(pingInterval, (_) {
_ping();
});
}
}
if (!dequeueTimer.isActive) {
dequeueTimer = Timer.periodic(_dispatchSettings.dequeueInterval, (timer) {
_dequeue();
});
}
}
/// Iterate on the actions in the queue and send them to Matomo.
Future<void> dispatchActions() {
return _dequeue();
}
/// Drops all actions queued for dispatching.
void dropActions() {
queue.clear();
}
/// This will register a page view with [trackPageViewWithName] by using the
/// `context.widget.toStringShort()` as `actionName` value.
///
/// {@template pvid_screen_track_parameter}
/// [pvId] is a 6 character unique ID that can later be used to associate
/// other actions (like [trackEvent]) with this page view. If `null`,
/// a random id will be generated (recommended). Also see [attachLastScreenInfo].
/// {@endtemplate}
///
/// {@template campaign_and_path_track_parameter}
/// [path] is a string that identifies the path of the screen where this action
/// happend. If not `null`, it will be appended to [contentBase] to create a
/// URL. This combination corresponds with `url`. Also see [attachLastScreenInfo].
/// Setting [path] manually will take precedance over [attachLastScreenInfo].
///
/// [campaign] can be a campaign that lead to this action. Setting this multiple
/// times during an apps lifetime can have some side effects, see the [Campaign]
/// class for more information.
/// {@endtemplate}
///
/// {@template dimensions_track_parameter}
/// For remarks on [dimensions] see [trackDimensions].
/// {@endtemplate}
///
/// {@template new_visit_track_parameter}
/// The [newVisit] parameter can be used to make this action the begin
/// of a new visit. If it's left to `null` and this is the first `track...`
/// call after [MatomoTracker.initialize], the `newVisit` from there will
/// be used.
/// {@endtemplate}
void trackPageView({
required BuildContext context,
String? pvId,
String? path,
Campaign? campaign,
Map<String, String>? dimensions,
PerformanceInfo? performanceInfo,
bool? newVisit,
}) {
final actionName = context.widget.toStringShort();
trackPageViewWithName(
actionName: actionName,
pvId: pvId,
path: path,
campaign: campaign,
dimensions: dimensions,
performanceInfo: performanceInfo,
newVisit: _inferNewVisit(newVisit),
);
}
/// Registers a page view.
///
/// [actionName] represents the page name, here used to identify the
/// screen with a proper name. Corresponds with `action_name`.
///
/// {@macro pvid_screen_track_parameter}
///
/// {@macro campaign_and_path_track_parameter}
///
/// {@macro dimensions_track_parameter}
///
/// {@macro new_visit_track_parameter}
void trackPageViewWithName({
required String actionName,
String? pvId,
String? path,
Campaign? campaign,
Map<String, String>? dimensions,
PerformanceInfo? performanceInfo,
bool? newVisit,
}) {
_initializationCheck();
if (pvId != null && pvId.length != 6) {
throw ArgumentError.value(
pvId,
'pvId',
'The pvId must be 6 characters long.',
);
}
validateDimension(dimensions);
final lastPageView = MatomoAction(
action: actionName,
path: path,
campaign: campaign,
dimensions: dimensions,
userLocale: userLocale,
pvId: pvId ?? randomAlphaNumeric(6),
performanceInfo: performanceInfo,
newVisit: _inferNewVisit(newVisit),
);
_lastPageView = lastPageView;
return _track(lastPageView);
}
/// Tracks a conversion for a goal.
///
/// The [id] corresponds with `idgoal` and [revenue] with `revenue`.
///
/// {@template pvid_other_track_parameter}
/// To associate this action with a page view, enable [attachLastScreenInfo] and
/// leave [pvId] to `null` here or set [pvId] to the [pvId] of that page view
/// manually, e.g. [TraceableClientMixin.pvId]. Setting [pvId] manually will
/// take precedance over [attachLastScreenInfo].
/// {@endtemplate}
///
/// {@macro campaign_and_path_track_parameter}
///
/// {@macro dimensions_track_parameter}
///
/// {@macro new_visit_track_parameter}
void trackGoal({
required int id,
double? revenue,
String? pvId,
String? path,
Campaign? campaign,
Map<String, String>? dimensions,
bool? newVisit,
}) {
_initializationCheck();
validateDimension(dimensions);
return _track(
MatomoAction(
goalId: id,
revenue: revenue,
pvId: _inferPvId(pvId),
path: _inferPath(path),
campaign: campaign,
dimensions: dimensions,
userLocale: userLocale,
newVisit: _inferNewVisit(newVisit),
),
);
}
/// Tracks an event.
///
/// {@macro pvid_other_track_parameter}
///
/// {@macro campaign_and_path_track_parameter}
///
/// {@macro dimensions_track_parameter}
///
/// {@macro new_visit_track_parameter}
void trackEvent({
required EventInfo eventInfo,
String? pvId,
String? path,
Campaign? campaign,
Map<String, String>? dimensions,
bool? newVisit,
}) {
validateDimension(dimensions);
return _track(
MatomoAction(
eventInfo: eventInfo,
pvId: _inferPvId(pvId),
path: _inferPath(path),
campaign: campaign,
dimensions: dimensions,
userLocale: userLocale,
newVisit: _inferNewVisit(newVisit),
),
);
}
/// Tracks custom dimensions.
///
/// It is recommended to set the `dimensions` parameter in one of the other
/// track calls instead of using this method (since it will log an additional
/// page view).
///
/// The keys of the [dimensions] map correspond with the `dimension[1-999]`
/// parameters. This means that the keys MUST be named `dimension1`,
/// `dimension2`, `...`.
///
/// The keys of the [dimensions] map will be validated if they follow these
/// rules, and if not, a [ArgumentError] will be thrown.
///
/// To see the dimensions in the Matomo dashboard, make sure to add them in the
/// dashboard first.
///
/// {@macro pvid_other_track_parameter}
///
/// {@macro campaign_and_path_track_parameter}
///
/// {@macro new_visit_track_parameter}
void trackDimensions({
required Map<String, String> dimensions,
String? pvId,
String? path,
Campaign? campaign,
bool? newVisit,
}) {
validateDimension(dimensions);
return _track(
MatomoAction(
pvId: _inferPvId(pvId),
path: _inferPath(path),
campaign: campaign,
dimensions: dimensions,
userLocale: userLocale,
newVisit: _inferNewVisit(newVisit),
),
);
}
/// Tracks a search.
///
/// [searchKeyword] corresponds with `search`, [searchCategory] with
/// `search_cat` and [searchCount] with `search_count`.
///
/// {@macro pvid_other_track_parameter}
///
/// {@macro campaign_and_path_track_parameter}
///
/// {@macro dimensions_track_parameter}
///
/// {@macro new_visit_track_parameter}
void trackSearch({
required String searchKeyword,
String? searchCategory,
int? searchCount,
String? pvId,
String? path,
Campaign? campaign,
Map<String, String>? dimensions,
bool? newVisit,
}) {
validateDimension(dimensions);
return _track(
MatomoAction(
searchKeyword: searchKeyword,
searchCategory: searchCategory,
searchCount: searchCount,
pvId: _inferPvId(pvId),
path: _inferPath(path),
campaign: campaign,
dimensions: dimensions,
userLocale: userLocale,
newVisit: _inferNewVisit(newVisit),
),
);
}
/// Tracks a cart update.
///
/// {@macro pvid_other_track_parameter}
///
/// {@macro campaign_and_path_track_parameter}
///
/// {@macro dimensions_track_parameter}
///
/// {@macro new_visit_track_parameter}
void trackCartUpdate({
List<TrackingOrderItem>? trackingOrderItems,
num? subTotal,
num? taxAmount,
num? shippingCost,
num? discountAmount,
double? grandTotal,
String? pvId,
String? path,
Campaign? campaign,
Map<String, String>? dimensions,
bool? newVisit,
}) {
_initializationCheck();
validateDimension(dimensions);
return _track(
MatomoAction(
// goalId should be set to 0 to track an ecommerce interaction
goalId: 0,
trackingOrderItems: trackingOrderItems,
subTotal: subTotal,
taxAmount: taxAmount,
shippingCost: shippingCost,
discountAmount: discountAmount,
revenue: grandTotal,
pvId: _inferPvId(pvId),
path: _inferPath(path),
campaign: campaign,
dimensions: dimensions,
userLocale: userLocale,
newVisit: _inferNewVisit(newVisit),
),
);
}
/// Tracks an ecommerce order.
///
/// [id] corresponds with `ec_id`, [trackingOrderItems] with `ec_items`,
/// [revenue] with `revenue`, [subTotal] with `ec_st`, [taxAmount] with
/// `ec_tx`, [shippingCost] with `ec_sh`, [discountAmount] with `ec_dt`.
///
/// {@macro pvid_other_track_parameter}
///
/// {@macro campaign_and_path_track_parameter}
///
/// {@macro dimensions_track_parameter}
///
/// {@macro new_visit_track_parameter}
void trackOrder({
required String id,
required double revenue,
List<TrackingOrderItem>? trackingOrderItems,
num? subTotal,
num? taxAmount,
num? shippingCost,
num? discountAmount,
String? pvId,
String? path,
Campaign? campaign,
Map<String, String>? dimensions,
bool? newVisit,
}) {
_initializationCheck();
validateDimension(dimensions);
return _track(
MatomoAction(
// goalId should be set to 0 to track an ecommerce interaction
goalId: 0,
orderId: id,
trackingOrderItems: trackingOrderItems,
revenue: revenue,
subTotal: subTotal,
taxAmount: taxAmount,
shippingCost: shippingCost,
discountAmount: discountAmount,
pvId: _inferPvId(pvId),
path: _inferPath(path),
campaign: campaign,
dimensions: dimensions,
userLocale: userLocale,
newVisit: _inferNewVisit(newVisit),
),
);
}
/// Tracks the click on an outgoing link.
///
/// [link] corresponds with `link`.
///
/// {@macro pvid_other_track_parameter}
///
/// {@macro campaign_and_path_track_parameter}
///
/// {@macro dimensions_track_parameter}
///
/// {@macro new_visit_track_parameter}
void trackOutlink({
required String link,
String? pvId,
String? path,
Campaign? campaign,
Map<String, String>? dimensions,
bool? newVisit,
}) {
_initializationCheck();
validateDimension(dimensions);
return _track(
MatomoAction(
link: link,
pvId: _inferPvId(pvId),
path: _inferPath(path),
campaign: campaign,
dimensions: dimensions,
userLocale: userLocale,
newVisit: _inferNewVisit(newVisit),
),
);
}
/// Tracks a content impression.
///
/// Later, if the user interacts with the content (e.g. taps on it),
/// call [trackContentInteraction].
///
/// {@macro pvid_other_track_parameter}
///
/// {@macro campaign_and_path_track_parameter}
///
/// {@macro dimensions_track_parameter}
///
/// {@macro new_visit_track_parameter}
void trackContentImpression({
required Content content,
String? pvId,
String? path,
Campaign? campaign,
Map<String, String>? dimensions,
bool? newVisit,
}) {
return _track(
MatomoAction(
content: content,
pvId: _inferPvId(pvId),
path: _inferPath(path),
campaign: campaign,
dimensions: dimensions,
userLocale: userLocale,
newVisit: _inferNewVisit(newVisit),
),
);
}
/// Tracks a content interaction.
///
/// Use [trackContentImpression] instead if the content was shown
/// to the user, but he did not interact with it.
///
/// The [interaction] corresponds with `c_i` and should
/// describe the type of interaction, e.g. `tap` or `swipe`.
///
/// {@macro pvid_other_track_parameter}
///
/// {@macro campaign_and_path_track_parameter}
///
/// {@macro dimensions_track_parameter}
///
/// Note that this method is missing a `newVisit` parameter on purpose since
/// it doesn't make sense to have an interaction without an impression first,
/// and then the impression would mark the new visit, not the interaction.
void trackContentInteraction({
required Content content,
required String interaction,
String? pvId,
String? path,
Campaign? campaign,
Map<String, String>? dimensions,
}) {
return _track(
MatomoAction(
content: content,
contentInteraction: interaction,
pvId: _inferPvId(pvId),
path: _inferPath(path),
campaign: campaign,
dimensions: dimensions,
userLocale: userLocale,
),
);
}
void _track(MatomoAction action) => queue.add(action.toMap(this));
void _ping() {
final lastPageView = _lastPageView;
if (lastPageView != null) {
_track(
lastPageView.copyWith(
ping: true,
newVisit: false,
),
);
}
}
Future<void> _dequeue() async {
if (!_initialized) {
throw const UninitializedMatomoInstanceException();
}
log.finest('Processing queue ${queue.length}');
if (!_lock.locked) {
return _lock.synchronized(() async {
final actions = List<Map<String, String>>.of(queue);
if (!_optOut) {
final hasSucceeded = await _dispatcher.sendBatch(
actions: actions,
customHeaders: customHeaders,
);
if (hasSucceeded) {
// As the operation is asynchronous we need to be sure to remove
// only the actions that were sent in the batch.
queue.removeWhere(actions.contains);
}
}
});
}
}
void _initializationCheck() {
if (!_initialized) {
throw const UninitializedMatomoInstanceException();
}
}
Future<void> _saveVisitorId(String? visitorId) async {
if (visitorId == null) return;
await _localStorage.setVisitorId(visitorId);
}
Future<String?> _getVisitorId() async {
/// The check is needed here as we don't want to create a new visitor id
/// with Uuid if the user has opted out.
if (_cookieless) return null;
final localId = await _localStorage.getVisitorId();
return localId ?? const Uuid().v4().replaceAll('-', '').substring(0, 16);
}
void _validateVisitorIdParameter({
required String? visitorId,
required VisitorIdParameter visitorIdParameter,