Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
fhdeodato committed Aug 9, 2024
2 parents 5be94b9 + e9c9cc3 commit f6fb2f5
Show file tree
Hide file tree
Showing 21 changed files with 193 additions and 114 deletions.
39 changes: 39 additions & 0 deletions .github/workflows/create_jira.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
name: Create Jira Ticket

on:
issues:
types:
- opened

jobs:
create_jira:
name: Create Jira Ticket
runs-on: ubuntu-latest
environment: IssueTracker
steps:
- name: Checkout
uses: actions/checkout@master
- name: Login
uses: atlassian/gajira-login@master
env:
JIRA_BASE_URL: ${{ secrets.JIRA_BASE_URL }}
JIRA_USER_EMAIL: ${{ secrets.JIRA_USER_EMAIL }}
JIRA_API_TOKEN: ${{ secrets.JIRA_TOKEN }}
JIRA_EPIC_KEY: ${{ secrets.JIRA_EPIC_KEY }}
JIRA_PROJECT: ${{ secrets.JIRA_PROJECT }}

- name: Create
id: create
uses: atlassian/gajira-create@master
with:
project: ${{ secrets.JIRA_PROJECT }}
issuetype: Bug
summary: |
[${{ github.event.repository.name }}] (${{ github.event.issue.number }}): ${{ github.event.issue.title }}
description: |
Github Link: ${{ github.event.issue.html_url }}
${{ github.event.issue.body }}
fields: '{"parent": {"key": "${{ secrets.JIRA_EPIC_KEY }}"}}'

- name: Log created issue
run: echo "Issue ${{ steps.create.outputs.issue }} was created"
2 changes: 1 addition & 1 deletion example/test/widget_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';

import 'package:segment_analytics_example/main.dart';
import 'package:analytics_example/main.dart';

void main() {
testWidgets('Verify Platform version', (WidgetTester tester) async {
Expand Down
15 changes: 8 additions & 7 deletions packages/core/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ You must pass at least the `writeKey`. Additional configuration options are list
### Client Options

| Name | Default | Description |
| --------------------------------- | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------- |
| --------------------------------- | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `writeKey` **(REQUIRED)** | '' | Your Segment API key. |
| `debug` | false | When set to false, it will not generate any info logs. |
| `collectDeviceId` | false | Set to true to automatically collect the device ID from the DRM API on Android devices. |
Expand All @@ -124,9 +124,10 @@ You must pass at least the `writeKey`. Additional configuration options are list
| `trackDeeplinks` | false | Enable automatic tracking for when the user opens the app via a deep link. \*NOTE: when sending this flag, the sdk plugin_appsflyer will ignore [onAppOpenAttribution](https://github.com/AppsFlyerSDK/appsflyer-flutter-plugin/blob/master/doc/Guides.md#Unified-deep-linking) |
| `autoAddSegmentDestination` | true | Set to false to skip adding the SegmentDestination plugin |
| `defaultIntegrationSettings` | null | Plugin settings that will be used if the request to get the settings from Segment fails. |
| `maxBatchSize` | true | 100 | Maximum number of events to send to the API at once. |
| `maxBatchSize` | true | 100 Maximum number of events to send to the API at once. |
| `appStateStream` | null | Set to override the stream of application foreground or background events. |
| `requestFactory` | true | Set to override the factory to generate HTTP requests. Type: [RequestFactory](https://github.com/segmentio/analytics_flutter/blob/master/packages/core/lib/state.dart#L546) |
| `storageJson` | true | Enable or disable automatic the generation JSON files for the serialization library |

## Client methods

Expand Down Expand Up @@ -524,7 +525,7 @@ LogFactory.logger = CustomLogger();

You can handle analytics client errors through the `errorHandler` option.

The error handler configuration receives a function which will get called whenever an error happens on the analytics client. It will receive an Exception, that will extend one of the errors from [errors.dart](packages/core/lib/errors.dart).
The error handler configuration receives a function which will get called whenever an error happens on the analytics client. It will receive an Exception, that will extend one of the errors from [errors.dart](./lib/errors.dart).

You can use this error handling to trigger different behaviours in the client when a problem occurs. For example if the client gets rate limited you could use the error handler to swap flush policies to be less aggressive:

Expand Down Expand Up @@ -554,7 +555,7 @@ final analytics = createClient(Configuration(writeKey),

### Reporting errors from plugins

Plugins can also report errors to the handler by using the [`.error`](packages/core/lib/analytics.dart#L52) function of the analytics client, we recommend using the `PluginError` for consistency, and attaching the `innerError` with the actual exception that was hit:
Plugins can also report errors to the handler by using the [`.error`](./lib/analytics.dart#L55) function of the analytics client, we recommend using the `PluginError` for consistency, and attaching the `innerError` with the actual exception that was hit:

```dart
import 'package:segment_analytics/errors.dart';
Expand All @@ -572,15 +573,15 @@ try {

## Example App

See the [example app](./example/README.md) to check a full test app of how to integrate Analytics-Flutter into your own Flutter app.
See the [example app](../../example/README.md) to check a full test app of how to integrate Analytics-Flutter into your own Flutter app.

## Contributing

See the [contributing guide](CONTRIBUTING.md) to learn how to contribute to the repository and the development workflow.
See the [contributing guide](./CONTRIBUTING.md) to learn how to contribute to the repository and the development workflow.

## Code of Conduct

Before contributing, please also see our [code of conduct](CODE_OF_CONDUCT.md).
Before contributing, please also see our [code of conduct](../../CODE_OF_CONDUCT.md).

## License

Expand Down
7 changes: 6 additions & 1 deletion packages/core/lib/analytics.dart
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import 'package:segment_analytics/version.dart';
import 'package:segment_analytics/utils/http_client.dart';
import 'package:segment_analytics/plugins/inject_user_info.dart';
import 'package:segment_analytics/plugins/inject_context.dart';
import 'package:segment_analytics/plugins/inject_token.dart';
import 'package:shared_preferences/shared_preferences.dart';

class Analytics with ClientMethods {
Expand Down Expand Up @@ -59,7 +60,7 @@ class Analytics with ClientMethods {
{HTTPClient Function(Analytics)? httpClient})
: _state = StateManager(_store, System(true, false), config),
_timeline = Timeline() {
_state.init(error);
_state.init(error, config.storageJson!);

this.httpClient = httpClient == null ? HTTPClient(this) : httpClient(this);

Expand All @@ -70,6 +71,10 @@ class Analytics with ClientMethods {
addPlugin(segmentDestination);
}

if(config.token != null) {
_platformPlugins.add(InjectToken(config.token!));
}

// Setup platform specific plugins
_platformPlugins.forEach(addPlugin);

Expand Down
32 changes: 16 additions & 16 deletions packages/core/lib/analytics_web.dart
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import 'dart:async';
import 'dart:html' as html show window;

import 'package:segment_analytics/native_context.dart';
import 'package:flutter_web_plugins/flutter_web_plugins.dart';

import 'package:segment_analytics/analytics_platform_interface.dart';
import 'package:segment_analytics/native_context.dart';
import 'package:web/web.dart' as web;

export 'package:segment_analytics/client.dart';

Expand All @@ -15,19 +14,20 @@ class AnalyticsPlatformImpl extends AnalyticsPlatform {

/// Returns a [String] containing the version of the platform.
@override
Future<NativeContext> getContext({bool collectDeviceId = false}) =>
Future.value(NativeContext(
app: NativeContextApp(
name: html.window.navigator.appName,
version: html.window.navigator.appVersion,
namespace: html.window.navigator.appCodeName),
userAgent: html.window.navigator.userAgent,
locale: html.window.navigator.language,
screen: html.window.screen != null
? NativeContextScreen(
height: html.window.screen?.height,
width: html.window.screen?.width)
: null));
Future<NativeContext> getContext({bool collectDeviceId = false}) async =>
NativeContext(
app: NativeContextApp(
name: web.window.navigator.appName,
version: web.window.navigator.appVersion,
namespace: web.window.navigator.appCodeName,
),
userAgent: web.window.navigator.userAgent,
locale: web.window.navigator.language,
screen: NativeContextScreen(
height: web.window.screen.height,
width: web.window.screen.width,
),
);
}

class AnalyticsWeb {
Expand Down
2 changes: 1 addition & 1 deletion packages/core/lib/client.dart
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ class ScreenObserver extends NavigatorObserver {

@override
void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
final name = route.settings.name;
final name = previousRoute?.settings.name;
if (name != null) {
screenStreamController.add(name);
}
Expand Down
17 changes: 17 additions & 0 deletions packages/core/lib/plugins/inject_token.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import 'package:segment_analytics/event.dart';
import 'package:segment_analytics/plugin.dart';

class InjectToken extends PlatformPlugin {
InjectToken(this.token) : super(PluginType.before);

final String token;

@override
Future<RawEvent> execute(RawEvent event) async {
// We need to get the Context in a concurrency safe mode to permit changes to make it in before we retrieve it
final context = await analytics!.state.context.state;
context!.device.token = token;
event.context = context;
return event;
}
}
2 changes: 1 addition & 1 deletion packages/core/lib/plugins/queue_flushing_plugin.dart
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ class QueueFlushingPlugin extends UtilityPlugin {
_state = QueueState("queue_flushing_plugin", analytics.store,
(json) => eventFromJson(json));

_state!.init(analytics.error);
_state!.init(analytics.error, true);
}

@override
Expand Down
47 changes: 30 additions & 17 deletions packages/core/lib/state.dart
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,11 @@ class StateManager {
final DeepLinkDataState deepLinkData;
final UserInfoState userInfo;

void init(ErrorHandler errorHandler) {
filters.init(errorHandler);
deepLinkData.init(errorHandler);
userInfo.init(errorHandler);
context.init(errorHandler);
void init(ErrorHandler errorHandler, bool storageJson) {
filters.init(errorHandler, storageJson);
deepLinkData.init(errorHandler, storageJson);
userInfo.init(errorHandler, storageJson);
context.init(errorHandler, storageJson);
}

StateManager(Store store, System system, Configuration configuration)
Expand Down Expand Up @@ -159,15 +159,17 @@ abstract class PersistedState<T> implements AsyncStateNotifier<T> {
}
}

void init(ErrorHandler errorHandler) {
void init(ErrorHandler errorHandler, bool storageJson) {
this._errorHandler = errorHandler;
addListener((state) {
if (_persistance != null) {
_hasUpdated = true;
} else {
_persistance = _store
.setPersisted(_key, toJson(state))
.whenComplete(_whenPersistenceComplete);
_persistance = storageJson
? _store
.setPersisted(_key, toJson(state))
.whenComplete(_whenPersistenceComplete)
: null;
}
});
_store.ready.then<void>((_) async {
Expand All @@ -176,9 +178,11 @@ abstract class PersistedState<T> implements AsyncStateNotifier<T> {

if (rawV == null) {
final init = await _initialiser();
_persistance = _store
.setPersisted(_key, toJson(init))
.whenComplete(_whenPersistenceComplete);
_persistance = storageJson
? _store
.setPersisted(_key, toJson(init))
.whenComplete(_whenPersistenceComplete)
: null;
_notifier.nonNullState = init;
v = init;
} else {
Expand All @@ -197,15 +201,16 @@ abstract class PersistedState<T> implements AsyncStateNotifier<T> {
return;
}).catchError((e) {
_error = e;
if (_error.toString().contains("FormatException")) {
// Clean file if exist a format error
if(_error.toString().contains("FormatException")) {
_store.setPersisted(_key, {});
log("Clean file $_key with format error", kind: LogFilterKind.warning);
log("Clean file $_key with format error",
kind: LogFilterKind.warning);
} else {
final wrappedError = ErrorLoadingStorage(e);
errorHandler(wrappedError);
throw wrappedError;
}

});
}

Expand Down Expand Up @@ -528,6 +533,9 @@ class Configuration {
final RequestFactory? requestFactory;
final StreamSubscription<AppStatus> Function()? appStateStream;
final ErrorHandler? errorHandler;
final bool? storageJson;

final String? token;

Configuration(this.writeKey,
{this.apiHost,
Expand All @@ -542,7 +550,10 @@ class Configuration {
this.trackApplicationLifecycleEvents = false,
this.trackDeeplinks = false,
this.debug = false,
this.maxBatchSize});
this.maxBatchSize,
this.storageJson = true,
this.token
});
}

typedef ErrorHandler = void Function(Exception);
Expand All @@ -561,5 +572,7 @@ Configuration setFlushPolicies(
maxBatchSize: a.maxBatchSize,
requestFactory: a.requestFactory,
trackApplicationLifecycleEvents: a.trackApplicationLifecycleEvents,
trackDeeplinks: a.trackDeeplinks);
trackDeeplinks: a.trackDeeplinks,
storageJson: a.storageJson,
token: a.token);
}
2 changes: 1 addition & 1 deletion packages/core/lib/utils/lifecycle/widget_observer.dart
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ class WidgetObserverLifecycle extends LifeCycle with WidgetsBindingObserver {
final StreamController<AppLifecycleState> _streamController =
StreamController<AppLifecycleState>.broadcast();

LifeCycleImpl() {
lifeCycleImpl() {
WidgetsBinding.instance.addObserver(this);
}

Expand Down
Loading

0 comments on commit f6fb2f5

Please sign in to comment.