|
| 1 | +import 'dart:convert'; |
| 2 | +import 'dart:io'; |
| 3 | +import 'dart:isolate'; |
| 4 | + |
| 5 | +import 'package:cryptography/cryptography.dart'; |
| 6 | +import 'package:http/http.dart' as http; |
| 7 | +import 'package:objectbox_generator/src/analysis/build_properties.dart'; |
| 8 | +import 'package:pubspec_parse/pubspec_parse.dart'; |
| 9 | + |
| 10 | +/// Sends anonymous data to analyze usage of this package. |
| 11 | +/// |
| 12 | +/// Requires [tokenFilePath] to exist, otherwise does nothing. See the |
| 13 | +/// associated test (analysis_test.dart) on how to create this file. |
| 14 | +class ObjectBoxAnalysis { |
| 15 | + static const _debug = false; |
| 16 | + |
| 17 | + /// Path is relative to lib folder. |
| 18 | + static const tokenFilePath = "assets/analysis-token.txt"; |
| 19 | + |
| 20 | + static const _url = "api.mixpanel.com"; |
| 21 | + static const _path = "track"; |
| 22 | + |
| 23 | + /// Builds a Build event and sends it with [sendEvent]. May not send if it |
| 24 | + /// fails to store a unique identifier and last time sent, or if no valid API |
| 25 | + /// token is found. |
| 26 | + Future<void> sendBuildEvent(Pubspec? pubspec) async { |
| 27 | + var buildProperties = await BuildProperties.get(); |
| 28 | + if (buildProperties == null) { |
| 29 | + buildProperties = BuildProperties.create(); |
| 30 | + } else { |
| 31 | + // Send at most one event per day. |
| 32 | + if (DateTime.now().millisecondsSinceEpoch < |
| 33 | + buildProperties.lastSentMs + Duration(days: 1).inMilliseconds) { |
| 34 | + if (_debug) { |
| 35 | + print("[ObjectBox] Analysis event sent within last day, skip."); |
| 36 | + } |
| 37 | + return; |
| 38 | + } |
| 39 | + buildProperties = BuildProperties.updateLastSentMs(buildProperties); |
| 40 | + } |
| 41 | + if (!await buildProperties.write()) { |
| 42 | + if (_debug) { |
| 43 | + print("[ObjectBox] Analysis failed to save build properties."); |
| 44 | + } |
| 45 | + return; |
| 46 | + } |
| 47 | + |
| 48 | + final event = buildEvent("Build", buildProperties.uid, pubspec); |
| 49 | + |
| 50 | + final response = await sendEvent(event); |
| 51 | + if (_debug && response != null) { |
| 52 | + print( |
| 53 | + "[ObjectBox] Analysis response: ${response.statusCode} ${response.body}"); |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + /// Sends an [Event] and returns the response. May return null if the API |
| 58 | + /// token could not be obtained. |
| 59 | + Future<http.Response?> sendEvent(Event event) async { |
| 60 | + final token = await _getToken(); |
| 61 | + if (token == null || token.isEmpty) { |
| 62 | + print("[ObjectBox] Analysis disabled, would have sent event: $event"); |
| 63 | + return null; |
| 64 | + } |
| 65 | + event.properties["token"] = token; |
| 66 | + |
| 67 | + // https://developer.mixpanel.com/reference/track-event |
| 68 | + final body = "[${event.toJson()}]"; |
| 69 | + final url = Uri.https(_url, _path); |
| 70 | + if (_debug) print("[ObjectBox] Analysis sending to $url: $body"); |
| 71 | + return http.post(url, |
| 72 | + headers: {'Accept': 'text/plain', 'Content-Type': 'application/json'}, |
| 73 | + body: body); |
| 74 | + } |
| 75 | + |
| 76 | + /// Uses the given values to gather properties and return them as an [Event]. |
| 77 | + Event buildEvent(String eventName, String distinctId, Pubspec? pubspec) { |
| 78 | + final properties = <String, String>{}; |
| 79 | + properties["distinct_id"] = distinctId; |
| 80 | + |
| 81 | + properties["Tool"] = "Dart Generator"; |
| 82 | + // This is (in most cases) not the actually used version, |
| 83 | + // but the version range allowed. |
| 84 | + final obxDep = pubspec?.dependencies["objectbox"]; |
| 85 | + if (obxDep != null && obxDep is HostedDependency) { |
| 86 | + properties["Version"] = obxDep.version.toString(); |
| 87 | + } |
| 88 | + |
| 89 | + final dartVersion = RegExp('([0-9]+).([0-9]+).([0-9]+)') |
| 90 | + .firstMatch(Platform.version) |
| 91 | + ?.group(0); |
| 92 | + properties["Dart"] = dartVersion ?? "unknown"; |
| 93 | + // true or false is enough as Dart version above is tied closely to a |
| 94 | + // specific Flutter release (see https://docs.flutter.dev/development/tools/sdk/releases). |
| 95 | + final hasFlutter = pubspec?.dependencies["flutter"] != null; |
| 96 | + properties["Flutter"] = hasFlutter.toString(); |
| 97 | + |
| 98 | + properties["BuildOS"] = Platform.operatingSystem; |
| 99 | + properties["BuildOSVersion"] = Platform.operatingSystemVersion; |
| 100 | + |
| 101 | + // Note: If no CI detected, do not set CI property. |
| 102 | + final ci = Platform.environment["CI"]; |
| 103 | + if (ci != null) { |
| 104 | + properties["CI"] = ci; |
| 105 | + } |
| 106 | + |
| 107 | + // If ISO code (xx-XX or xx_XX format), split into lang and region. |
| 108 | + // Otherwise set to unknown. |
| 109 | + final locale = Platform.localeName; |
| 110 | + var splitLocale = |
| 111 | + locale.contains("_") ? locale.split("_") : locale.split("-"); |
| 112 | + properties["lang"] = splitLocale.isNotEmpty ? splitLocale[0] : "unknown"; |
| 113 | + properties["c"] = splitLocale.length >= 2 ? splitLocale[1] : "unknown"; |
| 114 | + |
| 115 | + return Event(eventName, properties); |
| 116 | + } |
| 117 | + |
| 118 | + Future<String?> _getToken() async { |
| 119 | + final uri = Uri.parse("package:objectbox_generator/$tokenFilePath"); |
| 120 | + final resolvedUri = await Isolate.resolvePackageUri(uri); |
| 121 | + if (resolvedUri != null) { |
| 122 | + final file = File.fromUri(resolvedUri); |
| 123 | + try { |
| 124 | + if (await file.exists()) { |
| 125 | + final lines = await file.readAsLines(); |
| 126 | + if (lines.length >= 2) { |
| 127 | + return decryptToken(lines[0], lines[1]); |
| 128 | + } |
| 129 | + } |
| 130 | + } catch (e) { |
| 131 | + // Ignore. |
| 132 | + } |
| 133 | + } |
| 134 | + return null; |
| 135 | + } |
| 136 | + |
| 137 | + /// Takes a Base64 encoded secret key and secret text (which is a [SecretBox] |
| 138 | + /// concatenation) and returns the decrypted text. |
| 139 | + Future<String> decryptToken( |
| 140 | + String secretKeyBase64, String secretTextBase64) async { |
| 141 | + final algorithm = Chacha20.poly1305Aead(); |
| 142 | + var secretKeyBytes = base64Decode(secretKeyBase64); |
| 143 | + final secretKey = SecretKeyData(secretKeyBytes); |
| 144 | + |
| 145 | + final secretBox = SecretBox.fromConcatenation( |
| 146 | + base64Decode(secretTextBase64), |
| 147 | + nonceLength: algorithm.nonceLength, |
| 148 | + macLength: algorithm.macAlgorithm.macLength); |
| 149 | + |
| 150 | + final clearText = await algorithm.decrypt(secretBox, secretKey: secretKey); |
| 151 | + |
| 152 | + return utf8.decode(clearText); |
| 153 | + } |
| 154 | +} |
| 155 | + |
| 156 | +/// Wrapper for data to be sent for analysis. Use [toJson] to return a |
| 157 | +/// JSON object representation. |
| 158 | +class Event { |
| 159 | + final String name; |
| 160 | + final Map<String, String> properties; |
| 161 | + |
| 162 | + /// See class documentation. |
| 163 | + Event(this.name, this.properties); |
| 164 | + |
| 165 | + /// Return this as a JSON object. |
| 166 | + String toJson() { |
| 167 | + final map = {'event': name, 'properties': properties}; |
| 168 | + return jsonEncode(map); |
| 169 | + } |
| 170 | + |
| 171 | + @override |
| 172 | + String toString() => toJson(); |
| 173 | +} |
0 commit comments