-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSyncpointModels.m
472 lines (366 loc) · 15.1 KB
/
SyncpointModels.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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
//
// SyncpointModels.m
// Syncpoint
//
// Created by Jens Alfke on 3/7/12.
// Copyright (c) 2012 Couchbase, Inc. All rights reserved.
//
#import "SyncpointModels.h"
#import "SyncpointInternal.h"
#import "CouchModelFactory.h"
#import "TDMisc.h"
#import "CollectionUtils.h"
#import <Security/SecRandom.h>
@interface CouchModel (Internal)
- (CouchModel*) getModelProperty: (NSString*)property;
- (void) setModel: (CouchModel*)model forProperty: (NSString*)property;
@end
static NSString* randomString(void) {
uint8_t randomBytes[16]; // 128 bits of entropy
SecRandomCopyBytes(kSecRandomDefault, sizeof(randomBytes), randomBytes);
return TDHexFromBytes(randomBytes, sizeof(randomBytes));
}
//TODO: This would be useful as a method in CouchModelFactory or CouchDatabase...
static NSEnumerator* modelsOfType(CouchDatabase* database, NSString* type) {
NSEnumerator* e = [[database getAllDocuments] rows];
// LogTo(Syncpoint, @"modelsOfType %@ for database with %u docs", type, [[[database getAllDocuments] rows] count]);
return [e my_map: ^id(CouchQueryRow* row) {
if ([type isEqual: [row.documentProperties objectForKey: @"type"]]) {
CouchModel* model = [CouchModel modelForDocument: row.document];
if (!model) {
LogTo(Syncpoint, @"did you register a class for %@?",type);
}
return model;
}
else
return nil;
}];
}
@implementation SyncpointModel
@dynamic state;
- (bool) isActive {
return [self.state isEqual: @"active"];
}
// FIX: This name-mapping should be moved into CouchModel itself somehow.
- (CouchModel*) getModelProperty: (NSString*)property {
return [super getModelProperty: [property stringByAppendingString: @"_id"]];
}
- (void) setModel: (CouchModel*)model forProperty: (NSString*)property {
[super setModel: model forProperty: [property stringByAppendingString: @"_id"]];
}
+ (Class) classOfProperty: (NSString*)property {
if ([property hasSuffix: @"_id"])
property = [property substringToIndex: property.length-3];
return [super classOfProperty: property];
}
@end
@implementation SyncpointSession
@dynamic owner_id, oauth_creds, pairing_creds, channel_database, control_database, control_db_synced;
- (bool) isPaired {
return [self.state isEqual: @"paired"];
}
- (bool) isReadyToPair {
return !![self getValueOfProperty:@"pairing_token"];
}
+ (SyncpointSession*) sessionInDatabase: (CouchDatabase *)database {
NSString* sessID = [[NSUserDefaults standardUserDefaults] objectForKey:@"Syncpoint_SessionDocID"];
if (!sessID)
return nil;
CouchDocument* doc = [database documentWithID: sessID];
if (!doc)
return nil;
if (!doc.properties) {
// Oops -- the session ID in user-defaults is out of date, so clear it
[[NSUserDefaults standardUserDefaults] removeObjectForKey: @"Syncpoint_SessionDocID"];
return nil;
}
return [self modelForDocument: doc];
}
+ (SyncpointSession*) makeSessionInDatabase: (CouchDatabase*)database
appId: (NSString*)appId
multiChannel: (BOOL) multi
withRemoteServer: (NSURL*) remote
error: (NSError**)outError
{
// Register the other model classes with the database's model factory:
CouchModelFactory* factory = database.modelFactory;
[factory registerClass: @"SyncpointChannel" forDocumentType: @"channel"];
[factory registerClass: @"SyncpointSubscription" forDocumentType: @"subscription"];
[factory registerClass: @"SyncpointInstallation" forDocumentType: @"installation"];
LogTo(Syncpoint, @"Creating session for %@ in %@", appId, database);
SyncpointSession* session = [[self alloc] initWithNewDocumentInDatabase: database];
[session setValue: appId ofProperty: @"app_id"];
[session setValue: [remote absoluteString] ofProperty: @"syncpoint_url"];
session.state = @"new";
NSDictionary* oauth_creds = $dict({@"consumer_key", randomString()},
{@"consumer_secret", randomString()},
{@"token_secret", randomString()},
{@"token", randomString()});
session.oauth_creds = oauth_creds;
NSDictionary* pairingCreds = $dict({@"username", [@"pairing-" stringByAppendingString:randomString()]},
{@"password", randomString()});
session.pairing_creds = pairingCreds;
if (multi) {
[session setValue: @"multi-channel" ofProperty: @"pairing_mode"];
} else {
[session setValue: @"single-channel" ofProperty: @"pairing_mode"];
}
if (![[session save] wait: outError]) {
Warn(@"SyncpointSession: Couldn't save new session");
return nil;
}
NSString* sessionID = session.document.documentID;
LogTo(Syncpoint, @"...session ID = %@", sessionID);
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject: sessionID forKey: @"Syncpoint_SessionDocID"];
[defaults synchronize];
return session;
}
- (id) initWithDocument: (CouchDocument*)document {
self = [super initWithDocument: document];
if (self) {
// Register the other model classes with the database's model factory:
CouchModelFactory* factory = self.database.modelFactory;
[factory registerClass: @"SyncpointChannel" forDocumentType: @"channel"];
[factory registerClass: @"SyncpointSubscription" forDocumentType: @"subscription"];
[factory registerClass: @"SyncpointInstallation" forDocumentType: @"installation"];
}
return self;
}
- (NSDictionary*) pairingUserProperties {
NSString* username = [self.pairing_creds objectForKey:@"username"];
NSString* password = [self.pairing_creds objectForKey:@"password"];
NSAssert(username, @"needs the pairing username set first");
NSAssert(password, @"needs the pairing password set first");
return $dict({@"_id", $sprintf(@"org.couchdb.user:%@", username)},
{@"name", username},
{@"type", @"user"},
{@"sp_oauth",self.oauth_creds},
{@"pairing_state", @"new"},
{@"pairing_type",[self getValueOfProperty:@"pairing_type"]},
{@"pairing_mode",[self getValueOfProperty:@"pairing_mode"]},
{@"pairing_token",[self getValueOfProperty:@"pairing_token"]},
{@"pairing_app_id",[self getValueOfProperty:@"app_id"]},
{@"roles", [NSArray array]},
{@"password", password});
}
- (NSError*) error {
if (![self.state isEqual: @"error"])
return nil;
NSDictionary* errDict = [self getValueOfProperty: @"error"];
int code = [$castIf(NSNumber, [errDict objectForKey: @"errno"]) intValue];
NSString* message = $castIf(NSString, [errDict objectForKey: @"message"]);
return [NSError errorWithDomain: NSPOSIXErrorDomain
code: (code ? code : -1) // don't allow a zero code
userInfo: $dict({NSLocalizedDescriptionKey, message})];
}
- (BOOL) clearState: (NSError**)outError {
self.state = @"new";
[self setValue: nil ofProperty: @"error"];
return [[self save] wait: outError];
}
- (SyncpointChannel*) makeChannelWithName: (NSString*)name
error: (NSError**)outError
{
LogTo(Syncpoint, @"Create channel named '%@'", name);
SyncpointChannel* channel = [[SyncpointChannel alloc] initWithNewDocumentInDatabase: self.database];
[channel setValue: @"channel" ofProperty: @"type"];
if (self.owner_id) {
// [channel setValue: self.owner_id ofProperty: @"owner_id"];
channel.owner_id = self.owner_id;
channel.state = @"new";
} else {
channel.owner_id = @"unpaired";
channel.state = @"unpaired";
}
channel.name = name;
return [[channel save] wait: outError] ? channel : nil;
}
- (SyncpointChannel*) channelWithName: (NSString*)name andOwner: (NSString*)ownerId{
// TODO: Make this into a view query
LogTo(Syncpoint, @"Looking for channel named %@ with owner_id %@", name, ownerId);
for (SyncpointChannel* channel in modelsOfType(self.database, @"channel")) {
LogTo(Syncpoint, @"Saw channel named %@ with owner_id %@ and state %@", channel.name, channel.owner_id, channel.state);
if (![channel.state isEqual: @"error"] && [channel.name isEqual: name] && [channel.owner_id isEqual:ownerId])
return channel;
}
LogTo(Syncpoint, @"channelWithName %@ returning nil ", name);
return nil;
}
- (SyncpointChannel*) myChannelWithName: (NSString*)name {
id owner;
if (self.owner_id) {
owner = self.owner_id;
} else {
owner = @"unpaired";
}
return [self channelWithName:name andOwner:owner];
}
- (void) didFirstSyncOfControlDB {
if(!self.control_db_synced) {
self.control_db_synced = YES;
[[self save] wait: nil];
}
}
- (NSEnumerator*) readyChannels {
// TODO: Make this into a view query
return [modelsOfType(self.database, @"channel") my_map: ^(SyncpointChannel* channel) {
return channel.isReady ? channel : nil;
}];
}
- (NSEnumerator*) unpairedChannels {
// TODO: Make this into a view query
return [modelsOfType(self.database, @"channel") my_map: ^(SyncpointChannel* channel) {
return channel.unpaired ? channel : nil;
}];
}
- (NSEnumerator*) myChannels {
// TODO: Make this into a view query
return [modelsOfType(self.database, @"channel") my_map: ^(SyncpointChannel* channel) {
return ([channel.owner_id isEqual: self.owner_id]) ? channel : nil;
}];
}
- (NSEnumerator*) activeSubscriptions {
// TODO: Make this into a view query
// TODO: ensure the subscription.owner_id matches the session.owner_id
return [modelsOfType(self.database, @"subscription") my_map: ^(SyncpointSubscription* sub) {
return sub.isActive ? sub : nil;
}];
}
- (NSSet*) installedSubscriptions {
NSMutableSet* subscriptions = [NSMutableSet set];
for (SyncpointInstallation* inst in self.allInstallations)
[subscriptions addObject: inst.subscription];
return subscriptions;
}
- (NSEnumerator*) allInstallations {
// TODO: Make this into a view query
return [modelsOfType(self.database, @"installation") my_map: ^(SyncpointInstallation* inst) {
return ([inst.state isEqual: @"created"] && inst.session == self) ? inst : nil;
}];
}
@end
@implementation SyncpointChannel
@dynamic name, owner_id, cloud_database;
- (bool) isReady {
return [self.state isEqual: @"ready"];
}
- (bool) unpaired {
return [self.state isEqual: @"unpaired"];
}
- (SyncpointSubscription*) subscription {
// TODO: Make this into a view query
for (SyncpointSubscription* sub in modelsOfType(self.database, @"subscription"))
if (sub.channel == self)
return sub;
return nil;
}
- (CouchDatabase*) localDatabase {
SyncpointInstallation* inst = [self installation];
if (inst) {
return [inst localDatabase];
} else {
return nil;
}
}
- (CouchDatabase*) ensureLocalDatabase: (NSError**)outError
{
SyncpointSubscription *sub = [self subscription];
if (!sub) {
sub = [self subscribe: outError];
};
if (!sub) {
return nil;
}
if (![self localDatabase]) {
[sub makeInstallationWithLocalDatabase:nil error: outError];
}
CouchDatabase *database = [self localDatabase];
if (!database) {
return nil;
}
return database;
}
- (SyncpointInstallation*) installation {
// TODO: Make this into a view query
for (SyncpointInstallation* inst in modelsOfType(self.database, @"installation"))
if (inst.channel == self && inst.isLocal)
return inst;
return nil;
}
- (SyncpointSubscription*) subscribe: (NSError**)outError {
LogTo(Syncpoint, @"Subscribing to %@", self);
SyncpointSubscription* sub = [[SyncpointSubscription alloc] initWithNewDocumentInDatabase: self.database];
[sub setValue: @"subscription" ofProperty: @"type"];
sub.state = @"active";
[sub setValue: [self getValueOfProperty: @"owner_id"] ofProperty: @"owner_id"];
sub.channel = self;
return [[sub save] wait: outError] ? sub : nil;
}
@end
@implementation SyncpointSubscription
@dynamic channel, owner_id;
- (SyncpointInstallation*) installation {
return self.channel.installation;
}
- (SyncpointInstallation*) makeInstallationWithLocalDatabase: (CouchDatabase*)localDB
error: (NSError**)outError
{
NSString* name;
if (localDB)
name = localDB.relativePath;
else {
name = [@"channel-" stringByAppendingString: randomString()];
localDB = [self.database.server databaseNamed: name];
}
LogTo(Syncpoint, @"Installing %@ to %@", self, localDB);
if (![localDB ensureCreated: nil]) {
Warn(@"SyncpointSubscription could not create channel db %@", name);
return nil;
}
SyncpointInstallation* inst = [[SyncpointInstallation alloc] initWithNewDocumentInDatabase: self.database];
[inst setValue: @"installation" ofProperty: @"type"];
inst.state = @"created";
inst.session = [SyncpointSession sessionInDatabase: self.database];
inst.owner_id = self.owner_id;
// [inst setValue: [self getValueOfProperty: @"owner_id"] ofProperty: @"owner_id"];
inst.channel = self.channel;
inst.subscription = self;
[inst setValue: name ofProperty: @"local_db_name"];
return [[inst save] wait: outError] ? inst : nil;
}
- (BOOL) unsubscribe: (NSError**)outError {
SyncpointInstallation* inst = self.installation;
if (inst && ![inst uninstall: outError])
return NO;
return [[self deleteDocument] wait: outError];
//????: Is this how to do it?
}
@end
@implementation SyncpointInstallation
@dynamic subscription, channel, session, owner_id;
- (CouchDatabase*) localDatabase {
if (!self.isLocal)
return nil;
NSString* name = $castIf(NSString, [self getValueOfProperty: @"local_db_name"]);
return name ? [self.database.server databaseNamed: name] : nil;
}
- (bool) isLocal {
SyncpointSession* session = [SyncpointSession sessionInDatabase: self.database];
return [session.document.documentID isEqual: [self getValueOfProperty: @"session_id"]];
}
// Starts bidirectional sync of an application database with its server counterpart.
- (void) sync {
CouchDatabase *localChannelDb = self.localDatabase;
NSURL *cloudChannelURL = [NSURL URLWithString: self.channel.cloud_database
relativeToURL: [NSURL URLWithString:[self.session getValueOfProperty:@"syncpoint_url"]]];
LogTo(Syncpoint, @"Sync local db '%@' with remote %@", localChannelDb, cloudChannelURL);
NSArray* repls = [localChannelDb replicateWithURL: cloudChannelURL exclusively: NO];
for (CouchPersistentReplication* repl in repls)
repl.continuous = YES;
}
- (BOOL) uninstall: (NSError**)outError {
// todo delete the database file here
return [[self deleteDocument] wait: outError];
}
@end