-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
method_channel_firestore.dart
333 lines (290 loc) 路 10.2 KB
/
method_channel_firestore.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
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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
// ignore_for_file: require_trailing_commas
// Copyright 2017, the Chromium project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
// TODO(Lyokone): remove once we bump Flutter SDK min version to 3.3
// ignore: unnecessary_import
import 'dart:typed_data';
import 'package:_flutterfire_internals/_flutterfire_internals.dart';
import 'package:cloud_firestore_platform_interface/cloud_firestore_platform_interface.dart';
import 'package:cloud_firestore_platform_interface/src/method_channel/method_channel_load_bundle_task.dart';
import 'package:cloud_firestore_platform_interface/src/method_channel/method_channel_query_snapshot.dart';
import 'package:cloud_firestore_platform_interface/src/method_channel/utils/source.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/services.dart';
import 'method_channel_collection_reference.dart';
import 'method_channel_document_reference.dart';
import 'method_channel_query.dart';
import 'method_channel_transaction.dart';
import 'method_channel_write_batch.dart';
import 'utils/exception.dart';
import 'utils/firestore_message_codec.dart';
/// The entry point for accessing a Firestore.
///
/// You can get an instance by calling [FirebaseFirestore.instance].
class MethodChannelFirebaseFirestore extends FirebaseFirestorePlatform {
/// Create an instance of [MethodChannelFirebaseFirestore] with optional [FirebaseApp]
MethodChannelFirebaseFirestore({FirebaseApp? app}) : super(appInstance: app);
/// The [FirebaseApp] instance to which this [FirebaseDatabase] belongs.
///
/// If null, the default [FirebaseApp] is used.
/// The [MethodChannel] used to communicate with the native plugin
static MethodChannel channel = const MethodChannel(
'plugins.flutter.io/firebase_firestore',
StandardMethodCodec(FirestoreMessageCodec()),
);
/// The [EventChannel] used for query snapshots
static EventChannel querySnapshotChannel(String id) {
return EventChannel(
'plugins.flutter.io/firebase_firestore/query/$id',
const StandardMethodCodec(FirestoreMessageCodec()),
);
}
/// The [EventChannel] used for document snapshots
static EventChannel documentSnapshotChannel(String id) {
return EventChannel(
'plugins.flutter.io/firebase_firestore/document/$id',
const StandardMethodCodec(FirestoreMessageCodec()),
);
}
/// The [EventChannel] used for snapshotsInSync
static EventChannel snapshotsInSyncChannel(String id) {
return EventChannel(
'plugins.flutter.io/firebase_firestore/snapshotsInSync/$id',
const StandardMethodCodec(FirestoreMessageCodec()),
);
}
/// The [EventChannel] used for loadBundle
static EventChannel loadBundleChannel(String id) {
return EventChannel(
'plugins.flutter.io/firebase_firestore/loadBundle/$id',
const StandardMethodCodec(FirestoreMessageCodec()),
);
}
/// Gets a [FirebaseFirestorePlatform] with specific arguments such as a different
/// [FirebaseApp].
@override
FirebaseFirestorePlatform delegateFor({required FirebaseApp app}) {
return MethodChannelFirebaseFirestore(app: app);
}
@override
LoadBundleTaskPlatform loadBundle(Uint8List bundle) {
return MethodChannelLoadBundleTask(
task: channel.invokeMethod<String>('LoadBundle#snapshots'),
bundle: bundle,
firestore: this,
);
}
@override
Future<QuerySnapshotPlatform> namedQueryGet(
String name, {
GetOptions options = const GetOptions(),
}) async {
try {
final Map<String, dynamic>? data = await MethodChannelFirebaseFirestore
.channel
.invokeMapMethod<String, dynamic>(
'Firestore#namedQueryGet',
<String, dynamic>{
'name': name,
'firestore': FirebaseFirestorePlatform.instance,
'source': getSourceString(options.source),
},
);
return MethodChannelQuerySnapshot(
FirebaseFirestorePlatform.instance,
data!,
);
} catch (e, stack) {
if (e.toString().contains('Named query has not been found')) {
Error.throwWithStackTrace(
FirebaseException(
plugin: 'cloud_firestore',
code: 'non-existent-named-query',
message: 'Named query has not been found. '
'Please check it has been loaded properly via loadBundle().',
),
stack,
);
}
convertPlatformException(e, stack);
}
}
@override
WriteBatchPlatform batch() => MethodChannelWriteBatch(this);
@override
Future<void> clearPersistence() async {
try {
await channel
.invokeMethod<void>('Firestore#clearPersistence', <String, dynamic>{
'firestore': this,
});
} catch (e, stack) {
convertPlatformException(e, stack);
}
}
@override
Future<void> enablePersistence(
[PersistenceSettings? persistenceSettings]) async {
throw UnimplementedError(
'enablePersistence() is only available for Web. Use [Settings.persistenceEnabled] for other platforms.');
}
@override
CollectionReferencePlatform collection(String collectionPath) {
return MethodChannelCollectionReference(this, collectionPath);
}
@override
QueryPlatform collectionGroup(String collectionPath) {
return MethodChannelQuery(this, collectionPath,
isCollectionGroupQuery: true);
}
@override
Future<void> disableNetwork() async {
try {
await channel
.invokeMethod<void>('Firestore#disableNetwork', <String, dynamic>{
'firestore': this,
});
} catch (e, stack) {
convertPlatformException(e, stack);
}
}
@override
DocumentReferencePlatform doc(String documentPath) {
return MethodChannelDocumentReference(this, documentPath);
}
@override
Future<void> enableNetwork() async {
try {
await channel
.invokeMethod<void>('Firestore#enableNetwork', <String, dynamic>{
'firestore': this,
});
} catch (e, stack) {
convertPlatformException(e, stack);
}
}
@override
Stream<void> snapshotsInSync() {
StreamSubscription<dynamic>? snapshotStreamSubscription;
late StreamController<void> controller; // ignore: close_sinks
controller = StreamController<void>.broadcast(
onListen: () async {
final observerId = await MethodChannelFirebaseFirestore.channel
.invokeMethod<String>('SnapshotsInSync#setup');
snapshotStreamSubscription =
MethodChannelFirebaseFirestore.snapshotsInSyncChannel(observerId!)
.receiveGuardedBroadcastStream(
arguments: <String, dynamic>{'firestore': this},
onError: convertPlatformException,
).listen(
(event) => controller.add(null),
onError: controller.addError,
);
},
onCancel: () {
snapshotStreamSubscription?.cancel();
},
);
return controller.stream;
}
@override
Future<T> runTransaction<T>(
TransactionHandler<T> transactionHandler, {
Duration timeout = const Duration(seconds: 30),
int maxAttempts = 5,
}) async {
assert(timeout.inMilliseconds > 0,
'Transaction timeout must be more than 0 milliseconds');
final String? transactionId =
await MethodChannelFirebaseFirestore.channel.invokeMethod<String>(
'Transaction#create',
);
Completer<T> completer = Completer();
// Will be set by the `transactionHandler`.
late T result;
final eventChannel = EventChannel(
'plugins.flutter.io/firebase_firestore/transaction/$transactionId',
const StandardMethodCodec(FirestoreMessageCodec()),
);
final snapshotStreamSubscription =
eventChannel.receiveGuardedBroadcastStream(
arguments: <String, dynamic>{
'firestore': this,
'timeout': timeout.inMilliseconds,
'maxAttempts': maxAttempts,
},
onError: convertPlatformException,
).listen(
(event) async {
if (event['error'] != null) {
completer.completeError(
FirebaseException(
plugin: 'cloud_firestore',
code: event['error']['code'],
message: event['error']['message'],
),
);
return;
} else if (event['complete'] == true) {
completer.complete(result);
return;
}
final TransactionPlatform transaction =
MethodChannelTransaction(transactionId!, event['appName']);
// If the transaction fails on Dart side, then forward the error
// right away and only inform native side of the error.
try {
result = await transactionHandler(transaction) as T;
} catch (error, stack) {
// Signal native that a user error occurred, and finish the
// transaction
await MethodChannelFirebaseFirestore.channel
.invokeMethod('Transaction#storeResult', <String, dynamic>{
'transactionId': transactionId,
'result': {
'type': 'ERROR',
}
});
// Allow the [runTransaction] method to listen to an error.
completer.completeError(error, stack);
return;
}
// Send the transaction commands to Dart.
await MethodChannelFirebaseFirestore.channel
.invokeMethod('Transaction#storeResult', <String, dynamic>{
'transactionId': transactionId,
'result': {
'type': 'SUCCESS',
'commands': transaction.commands,
},
});
},
);
return completer.future.whenComplete(snapshotStreamSubscription.cancel);
}
@override
Settings settings = const Settings();
@override
Future<void> terminate() async {
try {
await channel.invokeMethod<void>('Firestore#terminate', <String, dynamic>{
'firestore': this,
});
} catch (e, stack) {
convertPlatformException(e, stack);
}
}
@override
Future<void> waitForPendingWrites() async {
try {
await channel.invokeMethod<void>(
'Firestore#waitForPendingWrites', <String, dynamic>{
'firestore': this,
});
} catch (e, stack) {
convertPlatformException(e, stack);
}
}
}