104 lines
2.9 KiB
Dart
104 lines
2.9 KiB
Dart
import 'package:flutter/foundation.dart';
|
|
import 'package:universal_io/io.dart'; // instead of 'dart:io';
|
|
import 'dart:convert';
|
|
|
|
/// Plausible class. Use the constructor to set the parameters.
|
|
class PlausibleTracker {
|
|
/// The url of your plausible server e.g. https://plausible.io
|
|
String serverUrl;
|
|
String userAgent;
|
|
String domain;
|
|
String screenWidth;
|
|
String xForwardedFor;
|
|
bool enabled = true;
|
|
|
|
/// Constructor
|
|
PlausibleTracker(this.serverUrl, this.domain,
|
|
{this.userAgent = "",
|
|
this.screenWidth = "",
|
|
this.xForwardedFor = "127.0.0.1"});
|
|
|
|
/// Post event to plausible
|
|
Future<int> event(
|
|
{String name = "pageview",
|
|
String referrer = "",
|
|
String page = "",
|
|
Map<String, String> props = const {}}) async {
|
|
if (!enabled) {
|
|
return 0;
|
|
}
|
|
|
|
// Post-edit parameters
|
|
int lastCharIndex = serverUrl.length - 1;
|
|
if (serverUrl.toString()[lastCharIndex] == '/') {
|
|
// Remove trailing slash '/'
|
|
serverUrl = serverUrl.substring(0, lastCharIndex);
|
|
}
|
|
page = "app://localhost/" + page;
|
|
referrer = "app://localhost/" + referrer;
|
|
|
|
// Get and set device infos
|
|
String version = Platform.operatingSystemVersion.replaceAll('"', '');
|
|
|
|
if (userAgent == "") {
|
|
userAgent = "Mozilla/5.0 ($version; rv:53.0) Gecko/20100101 Chrome/53.0";
|
|
}
|
|
|
|
// Http Post request see https://plausible.io/docs/events-api
|
|
try {
|
|
HttpClient client = HttpClient();
|
|
HttpClientRequest request =
|
|
await client.postUrl(Uri.parse(serverUrl + '/api/event'));
|
|
request.headers.set('User-Agent', userAgent);
|
|
request.headers.set('Content-Type', 'application/json; charset=utf-8');
|
|
request.headers.set('X-Forwarded-For', xForwardedFor);
|
|
Object body = {
|
|
"domain": domain,
|
|
"name": name,
|
|
"url": page,
|
|
"referrer": referrer,
|
|
"screen_width": screenWidth,
|
|
"props": props,
|
|
};
|
|
request.write(json.encode(body));
|
|
final HttpClientResponse response = await request.close();
|
|
client.close();
|
|
return response.statusCode;
|
|
} catch (e) {
|
|
if (kDebugMode) {
|
|
print(e);
|
|
}
|
|
}
|
|
|
|
return 1;
|
|
}
|
|
|
|
/// check if plausible is UP
|
|
Future<bool> hello() async {
|
|
try {
|
|
final client = HttpClient();
|
|
final request = await client.getUrl(Uri.parse(serverUrl + '/api/health'));
|
|
final response = await request.close();
|
|
|
|
if (response.statusCode == 200) {
|
|
final responseBody = await response.transform(utf8.decoder).join();
|
|
final json = jsonDecode(responseBody);
|
|
|
|
final clickhouseStatus = json['clickhouse'];
|
|
final postgresStatus = json['postgres'];
|
|
final sitesCacheStatus = json['sites_cache'];
|
|
|
|
return clickhouseStatus == 'ok' &&
|
|
postgresStatus == 'ok' &&
|
|
sitesCacheStatus == 'ok';
|
|
}
|
|
} catch (e) {
|
|
if (kDebugMode) {
|
|
print(e);
|
|
}
|
|
}
|
|
|
|
return false;
|
|
}
|
|
}
|