-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCWFirebaseCollection.m
373 lines (285 loc) · 12.2 KB
/
CWFirebaseCollection.m
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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
//
// CWFirebaseCollection.m
//
// Created by Clément Wehrung on 08/04/2014.
// Copyright (c) 2014 Clément Wehrung. All rights reserved.
//
#import <objc/runtime.h>
#import "CWFirebaseCollection.h"
#import "CWModel.h"
@interface CWFirebaseCollection()
@property (nonatomic, strong, readwrite) Firebase* reference;
@property (nonatomic, assign, readwrite) BOOL isLoading;
@property (nonatomic, assign, readwrite) BOOL hasMore;
@property (nonatomic, assign) BOOL isListeningNewChildren;
@property (nonatomic, strong) NSMutableDictionary *currentBatchModels;
@property (nonatomic, strong, readwrite) FDataSnapshot *lastDataSnapshot;
@property (nonatomic, strong) FDataSnapshot *startAtSnapshot;
@property (nonatomic, strong) NSOperationQueue *observersCancelQueue;
@end
@implementation CWFirebaseCollection
@dynamic dataSource, delegate;
- (id)initWithReference:(Firebase *)reference dataSource:(id <CWFirebaseCollectionDataSource>)dataSource
{
if (self = [super init])
{
_reference = reference;
_currentBatchModels = [NSMutableDictionary dictionary];
_observersCancelQueue = [[NSOperationQueue alloc] init];
_observersCancelQueue.suspended = YES;
_isLoading = NO;
_batchSize = 0;
_autoStartListeners = YES;
_hasMore = YES;
self.dataSource = dataSource;
}
return self;
}
- (id)copy
{
return [[[self class] alloc] initWithReference:self.reference dataSource:self.dataSource];;
}
- (void)dealloc
{
[self dispose];
}
- (void)dispose
{
self.observersCancelQueue.suspended = NO;
}
- (NSString *)description
{
return self.reference.description;
}
- (void)startListenersWithQuery:(FQuery *)query
{
[self listenNewChildren];
[self setupListenerWithQuery:query eventType:FEventTypeChildChanged selector:@selector(remoteModelDidChangeWithSnapshot:)];
[self setupListenerWithQuery:query eventType:FEventTypeChildMoved selector:@selector(remoteModelDidChangeWithSnapshot:)];
[self setupListenerWithQuery:query eventType:FEventTypeChildRemoved selector:@selector(removeModelWithSnapshot:)];
}
- (void)listenNewChildren
{
if (self.isListeningNewChildren) { return; }
else { self.isListeningNewChildren = YES; }
FQuery *query = nil;
if (!self.startAtSnapshot) {
query = self.reference;
}
else if (self.isAscending) {
query = [[self.reference queryOrderedByPriority] queryEndingAtValue:self.startAtSnapshot.priority childKey:self.startAtSnapshot.key];
}
else {
query = [[self.reference queryOrderedByPriority] queryStartingAtValue:self.startAtSnapshot.priority childKey:self.startAtSnapshot.key];
}
__weak CWFirebaseCollection *weakSelf = self;
FirebaseHandle handle;
handle = [query observeEventType:FEventTypeChildAdded withBlock:^(FDataSnapshot *snapshot) {
if ([snapshot.key isEqualToString:weakSelf.startAtSnapshot.key]) {
return;
}
__block BOOL processed = NO;
[weakSelf.dataSource collection:weakSelf prepareModelWithData:snapshot completion:^(id <CWCollectionModelProtocol> model, FDataSnapshot *snapshot) {
if (!model) { return; }
if ([weakSelf hasModel:model]) {
[weakSelf updateModel:model silent:NO];
} else if (!processed) {
// If a model has already been processed, it should never be added again
// Otherwise, a model could have been removed in the meantime, but receive
// echo from prepareModelWithData:completion: as it may be still listening to somethig else
// TODO: it would be nice to receive a cancellable FOperation: we could cancel it from here
[weakSelf addModel:model];
}
processed = YES;
}];
}];
[self.observersCancelQueue addOperationWithBlock:^{
[query removeObserverWithHandle:handle];
}];
}
- (void)setupListenerWithQuery:(FQuery *)query eventType:(FEventType)eventType selector:(SEL)selector
{
__weak CWFirebaseCollection *weakSelf = self;
FirebaseHandle handle;
handle = [query observeEventType:eventType withBlock:^(FDataSnapshot *snapshot) {
if ([weakSelf respondsToSelector:selector]) {
IMP imp = class_getMethodImplementation(weakSelf.class, selector);
void (*func)(id, SEL, FDataSnapshot *) = (void *)imp;
func(weakSelf, selector, snapshot);
}
}];
[self.observersCancelQueue addOperationWithBlock:^{
[query removeObserverWithHandle:handle];
}];
}
- (void)removeModelWithSnapshot:(FDataSnapshot *)snapshot
{
[self removeModelWithIdentifier:snapshot.key];
}
- (void)remoteModelDidChangeWithSnapshot:(FDataSnapshot *)snapshot
{
__weak CWFirebaseCollection *weakSelf = self;
[self.dataSource collection:self prepareModelWithData:snapshot completion:^(id <CWCollectionModelProtocol> model, FDataSnapshot *snapshot) {
if (model) {
[weakSelf updateModel:model];
}
}];
}
- (void)listen
{
[self loadAllWithCompletion:nil];
}
- (void)loadAllWithCompletion:(void (^)(CWCollection *collection, NSArray *models))completion
{
[self runQueryWithLimit:0 completion:completion];
}
- (void)loadMoreWithCompletion:(void (^)(CWCollection *collection, NSArray *models))completion
{
[self runQueryWithLimit:self.batchSize completion:completion];
}
- (void)runQueryWithLimit:(NSUInteger)limit completion:(void (^)(CWCollection *collection, NSArray *models))completion
{
void(^errorBlock)() = ^() {
if (completion) {
completion(self, @[]);
}
};
if (self.isLoading || !self.hasMore) { return errorBlock(); }
else { self.isLoading = YES; }
[self.currentBatchModels removeAllObjects];
FQuery *query = self.reference;
NSString *startDataSnapshotName = nil;
if (limit) {
query = self.isAscending ? [query queryLimitedToFirst:limit] : [query queryLimitedToLast:limit];
}
if (self.lastDataSnapshot)
{
query = [[query queryOrderedByPriority] queryEndingAtValue:self.lastDataSnapshot.priority childKey:self.lastDataSnapshot.key];
startDataSnapshotName = self.lastDataSnapshot.key;
}
__weak CWFirebaseCollection *weakSelf = self;
__block BOOL batchLoading = YES;
[query observeSingleEventOfType:FEventTypeValue withBlock:^(FDataSnapshot *snapshot) {
__block NSUInteger totalCount = snapshot.childrenCount - (weakSelf.lastDataSnapshot ? 1 : 0);
__block NSMutableDictionary *preparedSnapshots = [NSMutableDictionary dictionary];
void (^readyBlock)() = ^() {
weakSelf.isLoading = batchLoading = NO;
if (!limit || totalCount < limit - 1) {
weakSelf.hasMore = NO;
}
for (id <CWCollectionModelProtocol> model in weakSelf.currentBatchModels.allValues)
{
if (![weakSelf hasModel:model]) {
[weakSelf addModel:model];
} else {
[weakSelf updateModel:model silent:YES];
}
}
if (completion) {
completion(weakSelf, weakSelf.currentBatchModels.allValues);
}
[weakSelf startListenersWithQuery:query];
[weakSelf.currentBatchModels removeAllObjects];
preparedSnapshots = nil;
};
if (!totalCount) {
return readyBlock();
}
/**
* completionBlock takes care of complex situations linked with offline cache,
* where the completionBlock may be called several times for the same snapshot.
* If the model has already been created, it will update it silently.
*/
void (^completionBlock)(id <CWCollectionModelProtocol>, FDataSnapshot *snapshot) = ^(id <CWCollectionModelProtocol> model, FDataSnapshot *snapshot)
{
if (!batchLoading) {
// Query already completed, but receives new data updates.
// This is due to Firebase Offline cache which forces us to accept
// multiple completion callbacks per location (1. cache, 2. remote value).
// Yet, once we have received 1 callback per location, the query is
// considered completed (otherwise, it may never complete: e.g. if one child
// was indeed removed, it won't be called twice with NSNull)
return model ? [weakSelf updateModel:model silent:NO] : nil;
}
if (snapshot) {
if (preparedSnapshots[snapshot.key]) return;
else [preparedSnapshots setObject:@(YES) forKey:snapshot.key];
}
if (model) {
[weakSelf.currentBatchModels setObject:model forKey:model.identifier];
}
if (preparedSnapshots.count == totalCount) {
readyBlock();
}
};
if (!snapshot.childrenCount) {
return completionBlock(nil, nil);
}
NSUInteger enumIndex = 0;
NSUInteger lastDataIndex = weakSelf.isAscending ? (snapshot.childrenCount - 1) : 0;
NSUInteger firstDataIndex = weakSelf.isAscending ? 0 : (snapshot.childrenCount - 1);
// TODO: snapshot.children should be reversed if not ascending
// But snapshot.children.allObjects.reverseEnumerator does not seem to work for now
// Maybe Firebase SDK could offer snapshot.reverseChildren?
for (FDataSnapshot *childSnapshot in snapshot.children) {
if (startDataSnapshotName != childSnapshot.key)
{
if (enumIndex == lastDataIndex) {
weakSelf.lastDataSnapshot = childSnapshot;
}
else if (enumIndex == firstDataIndex) {
weakSelf.startAtSnapshot = childSnapshot;
}
if ([childSnapshot.value isKindOfClass:NSNull.class]) {
completionBlock(nil, snapshot);
} else {
[weakSelf.dataSource collection:weakSelf prepareModelWithData:childSnapshot completion:completionBlock];
}
}
enumIndex++;
}
} withCancelBlock:^(NSError *error) {
errorBlock();
}];
}
- (void)modelAdded:(id <CWCollectionModelProtocol>)model atIndex:(NSUInteger)index
{
[super modelAdded:model atIndex:index];
BOOL inBatch = [self.currentBatchModels objectForKey:model.identifier] != nil;
if ([self.delegate respondsToSelector:@selector(collection:modelAdded:atIndex:inBatch:)]) {
[self.delegate collection:self modelAdded:model atIndex:index inBatch:inBatch];
}
}
- (void)setIsLoading:(BOOL)isLoading
{
_isLoading = isLoading;
SEL selector = isLoading ? @selector(collectionDidStartLoad:) : @selector(collectionDidEndLoad:);
if ([self.delegate respondsToSelector:selector]) {
IMP imp = class_getMethodImplementation(self.delegate.class, selector);
void (*func)(id, SEL, CWCollection *) = (void *)imp;
func(self.delegate, selector, self);
}
}
#pragma mark - Default Model Implementation
- (void)collection:(CWCollection *)collection prepareModelWithData:(FDataSnapshot *)snapshot completion:(CWCollectionPrepareResult)completionBlock
{
assert(self.modelClass);
id model = nil;
if (snapshot && ![snapshot isKindOfClass:NSNull.class]) {
Class class = self.modelClass;
model = [[class alloc] initWithIdentifier:snapshot.key];
[model updateWithDictionary:snapshot.valueInExportFormat];
}
completionBlock(model, snapshot);
}
#pragma mark - Model
- (void)addModel:(id <CWCollectionModelProtocol>)model
{
if (!model.identifier) {
Firebase *modelRef = [self.reference childByAutoId];
model.identifier = modelRef.key;
[modelRef setValue:model.dictionary];
}
return [self addModel:model silent:NO];
}
@end