forked from flutter/devtools
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsurvey.dart
More file actions
268 lines (229 loc) · 8.18 KB
/
survey.dart
File metadata and controls
268 lines (229 loc) · 8.18 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
// Copyright 2020 The Flutter Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file or at https://developers.google.com/open-source/licenses/bsd.
import 'dart:convert';
import 'package:devtools_shared/devtools_shared.dart';
import 'package:flutter/widgets.dart';
import 'package:http/http.dart';
import 'package:logging/logging.dart';
import '../analytics/analytics.dart' as ga;
import '../development_helpers.dart';
import '../globals.dart';
import '../primitives/utils.dart';
import '../server/server.dart' as server;
import '../utils/utils.dart';
import 'notifications.dart';
final _log = Logger('survey');
class SurveyService {
static const _noThanksLabel = 'No thanks';
static const _takeSurveyLabel = 'Take survey';
static const _maxShowSurveyCount = 5;
/// The URL that we will fetch the DevTools survey metadata from.
///
/// To run new surveys, update the content at
/// https://github.com/flutter/uxr/blob/master/surveys/devtools-survey-metadata.json.
///
/// This content will be propagated to the storage.googleapis.com domain
/// automatically.
static final _metadataUrl = Uri.https(
'storage.googleapis.com',
'flutter-uxr/surveys/devtools-survey-metadata.json',
);
/// Duration for which we should show the survey notification.
///
/// We use a very long time here to give the appearance of a persistent
/// notification. The user will need to interact with the prompt to dismiss
/// it.
static const _notificationDuration = Duration(days: 1);
DevToolsSurvey? _cachedSurvey;
Future<DevToolsSurvey?> get activeSurvey async {
// If the server is unavailable we don't need to do anything survey related.
if (!server.isDevToolsServerAvailable && !debugSurvey) return null;
_cachedSurvey ??= await fetchSurveyContent();
if (_cachedSurvey?.id != null) {
// TODO(kenz): consider setting this value on the [SurveyService] and then
// we can send the active survey as a parameter in each survey-related
// DevTools server request. This would simplify the server API for
// DevTools surveys.
await server.setActiveSurvey(_cachedSurvey!.id!);
}
if (await _shouldShowSurvey()) {
return _cachedSurvey;
}
return null;
}
void maybeShowSurveyPrompt() async {
final survey = await activeSurvey;
if (survey != null) {
final message = survey.title!;
final actions = [
NotificationAction(
label: _noThanksLabel,
onPressed: () => _noThanksPressed(message: message),
),
NotificationAction(
label: _takeSurveyLabel,
onPressed:
() => _takeSurveyPressed(
surveyUrl: _generateSurveyUrl(survey.url!),
message: message,
),
isPrimary: true,
),
];
WidgetsBinding.instance.addPostFrameCallback((_) {
final didPush = notificationService.pushNotification(
NotificationMessage(
message,
actions: actions,
duration: _notificationDuration,
),
allowDuplicates: false,
);
if (didPush) {
safeUnawaited(server.incrementSurveyShownCount());
}
});
}
}
String _generateSurveyUrl(String surveyUrl) {
final uri = Uri.parse(surveyUrl);
final queryParams = ga.generateSurveyQueryParameters();
return Uri(
scheme: uri.scheme,
host: uri.host,
path: uri.path,
queryParameters: queryParams,
).toString();
}
Future<bool> _shouldShowSurvey() async {
if (_cachedSurvey == null) return false;
final surveyShownCount = await server.surveyShownCount();
if (surveyShownCount >= _maxShowSurveyCount) return false;
final surveyActionTaken = await server.surveyActionTaken();
if (surveyActionTaken) return false;
return _cachedSurvey!.shouldShow;
}
@visibleForTesting
Future<DevToolsSurvey?> fetchSurveyContent() async {
try {
if (debugSurvey) {
return debugSurveyMetadata;
}
final response = await get(_metadataUrl);
if (response.statusCode == 200) {
final contents = json.decode(response.body) as Map<String, Object?>;
return DevToolsSurvey.fromJson(contents);
}
} on Error catch (e, st) {
_log.shout('Error fetching survey content: $e', e, st);
}
return null;
}
void _noThanksPressed({required String message}) async {
await server.setSurveyActionTaken();
notificationService.dismiss(message);
}
void _takeSurveyPressed({
required String surveyUrl,
required String message,
}) async {
await launchUrlWithErrorHandling(surveyUrl);
await server.setSurveyActionTaken();
notificationService.dismiss(message);
}
}
class DevToolsSurvey {
DevToolsSurvey._(
this.id,
this.startDate,
this.endDate,
this.title,
this.url,
this.minDevToolsVersion,
this.devEnvironments,
);
factory DevToolsSurvey.fromJson(Map<String, Object?> json) {
final id = json[_uniqueIdKey] as String?;
final startDateAsString = json[_startDateKey] as String?;
final endDateAsString = json[_endDateKey] as String?;
final minVersionAsString = json[_minDevToolsVersionKey] as String?;
final startDate =
startDateAsString != null ? DateTime.parse(startDateAsString) : null;
final endDate =
endDateAsString != null ? DateTime.parse(endDateAsString) : null;
final title = json[_titleKey] as String?;
final surveyUrl = json[_urlKey] as String?;
final minDevToolsVersion =
minVersionAsString != null
? SemanticVersion.parse(minVersionAsString)
: null;
final devEnvironments =
(json[_devEnvironmentsKey] as List?)?.cast<String>().toList();
return DevToolsSurvey._(
id,
startDate,
endDate,
title,
surveyUrl,
minDevToolsVersion,
devEnvironments,
);
}
static const _uniqueIdKey = 'uniqueId';
static const _startDateKey = 'startDate';
static const _endDateKey = 'endDate';
static const _titleKey = 'title';
static const _urlKey = 'url';
static const _minDevToolsVersionKey = 'minDevToolsVersion';
static const _devEnvironmentsKey = 'devEnvironments';
final String? id;
final DateTime? startDate;
final DateTime? endDate;
final String? title;
/// The url for the survey that the user will open in a browser when they
/// respond to the survey prompt.
final String? url;
/// The minimum DevTools version that this survey should is for.
///
/// If the current version of DevTools is older than [minDevToolsVersion], the
/// survey prompt in DevTools will not be shown.
///
/// If [minDevToolsVersion] is null, the survey will be shown for any version
/// of DevTools as long as all the other requirements are satisfied.
final SemanticVersion? minDevToolsVersion;
/// A list of development environments to show the survey for (e.g. 'VSCode',
/// 'Android-Studio', 'IntelliJ-IDEA', 'CLI', etc.).
///
/// If [devEnvironments] is null, the survey can be shown to any platform.
///
/// The possible values for this list correspond to the possible values of
/// `_ideLaunched` from [shared/analytics/_analytics_web.dart].
final List<String>? devEnvironments;
}
extension ShowSurveyExtension on DevToolsSurvey {
bool get meetsDateRequirement =>
(startDate == null || endDate == null)
? false
: Range(
startDate!.millisecondsSinceEpoch,
endDate!.millisecondsSinceEpoch,
).contains(_currentClockTime().millisecondsSinceEpoch);
bool get meetsMinVersionRequirement =>
minDevToolsVersion == null ||
SemanticVersion.parse(
devToolsVersion,
).isSupported(minSupportedVersion: minDevToolsVersion!);
bool get meetsEnvironmentRequirement =>
devEnvironments == null ||
ga.ideLaunched.isEmpty ||
devEnvironments!.contains(ga.ideLaunched);
bool get shouldShow =>
meetsDateRequirement &&
meetsMinVersionRequirement &&
meetsEnvironmentRequirement;
}
DateTime _currentClockTime() => fakeClockTimeForSurvey ?? DateTime.now();
/// A hook to set a fake clock time for tests.
@visibleForTesting
DateTime? fakeClockTimeForSurvey;