-
Notifications
You must be signed in to change notification settings - Fork 33
/
web.dart
98 lines (84 loc) · 2.58 KB
/
web.dart
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
import 'dart:async';
import 'dart:convert';
import 'dart:html' as html;
import 'package:segment_analytics/utils/store/store.dart';
class StoreImpl implements Store {
html.Storage get localStorage => html.window.localStorage;
@override
Future<Map<String, dynamic>?> getPersisted(String key) {
return _readFromStorage(key);
}
@override
Future get ready => Future.value();
@override
Future setPersisted(String key, Map<String, dynamic> value) {
return _writeToStorage(key, value);
}
String _getFileName(String fileKey) {
return "analytics-flutter-$fileKey.json";
}
Future<void> _writeToStorage(
String fileKey, Map<String, dynamic> data) async {
localStorage.update(
_getFileName(fileKey),
(val) => json.encode(data),
ifAbsent: () => json.encode(data),
);
}
Future<Map<String, dynamic>?> _readFromStorage(String fileKey) async {
final fileName = _getFileName(fileKey);
MapEntry<String, String>? data;
String anonymousId;
try {
data = localStorage.entries.firstWhere((i) => i.key == fileName);
} on StateError {
data = null;
}
if(fileKey == "userInfo") {
anonymousId = getExistingAnonymousId(data);
if(data != null) {
final jsonDecoded = json.decode(data.value);
if(anonymousId.isNotEmpty){
jsonDecoded["anonymousId"] = anonymousId;
return jsonDecoded as Map<String, dynamic>;
}
} else if(anonymousId.isNotEmpty){
final json = {"anonymousId": anonymousId };
return json;
}
}
if (data != null) {
if (data.value == "{}") {
return null; // Prefer null to empty map, because we'll want to initialise a valid empty value.
}
return json.decode(data.value) as Map<String, dynamic>;
} else {
return null;
}
}
@override
void dispose() {}
String getExistingAnonymousId(MapEntry<String, String>? data) {
String anonymousId;
try {
final entry = localStorage.entries.firstWhere(
(i) => i.key == "ajs_anonymous_id",
);
anonymousId = entry.value;
} on StateError {
anonymousId = '';
}
if (anonymousId.isEmpty) {
final cookies = html.document.cookie?.split(";");
if (cookies != null && cookies.isNotEmpty) {
for (var cookie in cookies) {
final cookieParts = cookie.split("=");
if (cookieParts[0].trim() == "ajs_anonymous_id") {
anonymousId = cookieParts[1];
}
}
}
}
return anonymousId.isEmpty ? '' : anonymousId;
}
}