This repository has been archived by the owner on Mar 9, 2022. It is now read-only.
/
TD_Database+Attachments.m
656 lines (580 loc) · 26 KB
/
TD_Database+Attachments.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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
//
// TD_Database+Attachments.m
// TouchDB
//
// Created by Jens Alfke on 12/19/11.
// Copyright (c) 2011 Couchbase, Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
//
// http://wiki.apache.org/couchdb/HTTP_Document_API#Attachments
/*
Here's what an actual _attachments object from CouchDB 1.2 looks like.
The "revpos" and "digest" attributes aren't documented in the wiki (yet).
"_attachments":{
"index.txt":{"content_type":"text/plain", "revpos":1,
"digest":"md5-muNoTiLXyJYP9QkvPukNng==", "length":9, "stub":true}}
*/
#import "TD_Database+Attachments.h"
#import "TD_Database+Insertion.h"
#import "TDBase64.h"
#import "TDBlobStore.h"
#import "TD_Attachment.h"
#import "TD_Body.h"
#import "TDMultipartWriter.h"
#import "TDMisc.h"
#import "TDInternal.h"
#import "CollectionUtils.h"
#import "FMDatabase.h"
#import "FMDatabaseAdditions.h"
#import "FMResultSet.h"
#import "GTMNSData+zlib.h"
// Length that constitutes a 'big' attachment
#define kBigAttachmentLength (16*1024)
@implementation TD_Database (Attachments)
- (TDBlobStoreWriter*) attachmentWriter {
return [[TDBlobStoreWriter alloc] initWithStore: _attachments];
}
- (void) rememberAttachmentWritersForDigests: (NSDictionary*)blobsByDigests {
if (!_pendingAttachmentsByDigest)
_pendingAttachmentsByDigest = [[NSMutableDictionary alloc] init];
[_pendingAttachmentsByDigest addEntriesFromDictionary: blobsByDigests];
}
- (void) rememberPendingKey: (TDBlobKey)key forDigest: (NSString*)digest {
if (!_pendingAttachmentsByDigest)
_pendingAttachmentsByDigest = [[NSMutableDictionary alloc] init];
NSData* keyData = [NSData dataWithBytes: &key length: sizeof(TDBlobKey)];
_pendingAttachmentsByDigest[digest] = keyData;
}
- (void) rememberAttachmentWriter: (TDBlobStoreWriter*)writer forDigest:(NSString*)digest {
if (!_pendingAttachmentsByDigest)
_pendingAttachmentsByDigest = [[NSMutableDictionary alloc] init];
_pendingAttachmentsByDigest[digest] = writer;
}
// This is ONLY FOR TESTS (see TDMultipartDownloader.m)
#if DEBUG
- (id) attachmentWriterForAttachment: (NSDictionary*)attachment {
NSString* digest = $castIf(NSString, attachment[@"digest"]);
if (!digest)
return nil;
return _pendingAttachmentsByDigest[digest];
}
#endif
- (TDStatus) installAttachment: (TD_Attachment*)attachment
forInfo: (NSDictionary*)attachInfo {
NSString* digest = $castIf(NSString, attachInfo[@"digest"]);
if (!digest)
return kTDStatusBadAttachment;
id writer = _pendingAttachmentsByDigest[digest];
if ([writer isKindOfClass: [TDBlobStoreWriter class]]) {
// Found a blob writer, so install the blob:
if (![writer install])
return kTDStatusAttachmentError;
attachment->blobKey = [writer blobKey];
attachment->length = [writer length];
// Remove the writer but leave the blob-key behind for future use:
[self rememberPendingKey: attachment->blobKey forDigest: digest];
return kTDStatusOK;
} else if ([writer isKindOfClass: [NSData class]]) {
// This attachment was already added, but the key was left behind in the dictionary:
attachment->blobKey = *(TDBlobKey*)[writer bytes];
NSNumber* lengthObj = $castIf(NSNumber, attachInfo[@"length"]);
if (!lengthObj)
return kTDStatusBadAttachment;
attachment->length = lengthObj.unsignedLongLongValue;
return kTDStatusOK;
} else {
return kTDStatusBadAttachment;
}
}
- (BOOL) storeBlob: (NSData*)blob creatingKey: (TDBlobKey*)outKey {
return [_attachments storeBlob: blob creatingKey: outKey];
}
- (TDStatus) insertAttachment: (TD_Attachment*)attachment
forSequence: (SequenceNumber)sequence
{
Assert(sequence > 0);
Assert(attachment.isValid);
NSData* keyData = [NSData dataWithBytes: &attachment->blobKey length: sizeof(TDBlobKey)];
id encodedLengthObj = attachment->encoding ? @(attachment->encodedLength) : nil;
if (![_fmdb executeUpdate: @"INSERT INTO attachments "
"(sequence, filename, key, type, encoding, length, encoded_length, revpos) "
"VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
@(sequence), attachment.name, keyData,
attachment.contentType, @(attachment->encoding),
@(attachment->length), encodedLengthObj,
@(attachment->revpos)]) {
return kTDStatusDBError;
}
return kTDStatusCreated;
}
- (TDStatus) copyAttachmentNamed: (NSString*)name
fromSequence: (SequenceNumber)fromSequence
toSequence: (SequenceNumber)toSequence
{
Assert(name);
Assert(toSequence > 0);
Assert(toSequence > fromSequence);
if (fromSequence <= 0)
return kTDStatusNotFound;
if (![_fmdb executeUpdate: @"INSERT INTO attachments "
"(sequence, filename, key, type, encoding, encoded_Length, length, revpos) "
"SELECT ?, ?, key, type, encoding, encoded_Length, length, revpos "
"FROM attachments WHERE sequence=? AND filename=?",
@(toSequence), name,
@(fromSequence), name]) {
return kTDStatusDBError;
}
if (_fmdb.changes == 0) {
// Oops. This means a glitch in our attachment-management or pull code,
// or else a bug in the upstream server.
Warn(@"Can't find inherited attachment '%@' from seq#%lld to copy to #%lld",
name, fromSequence, toSequence);
return kTDStatusNotFound; // Fail if there is no such attachment on fromSequence
}
return kTDStatusOK;
}
- (NSData*) decodeAttachment: (NSData*)attachment encoding: (TDAttachmentEncoding)encoding {
switch (encoding) {
case kTDAttachmentEncodingNone:
break;
case kTDAttachmentEncodingGZIP:
attachment = [NSData gtm_dataByInflatingData: attachment];
}
if (!attachment)
Warn(@"Unable to decode attachment!");
return attachment;
}
/** Returns the location of an attachment's file in the blob store. */
- (NSString*) getAttachmentPathForSequence: (SequenceNumber)sequence
named: (NSString*)filename
type: (NSString**)outType
encoding: (TDAttachmentEncoding*)outEncoding
status: (TDStatus*)outStatus
{
Assert(sequence > 0);
Assert(filename);
NSString* filePath = nil;
FMResultSet* r = [_fmdb executeQuery:
@"SELECT key, type, encoding FROM attachments WHERE sequence=? AND filename=?",
@(sequence), filename];
if (!r) {
*outStatus = kTDStatusDBError;
return nil;
}
@try {
if (![r next]) {
*outStatus = kTDStatusNotFound;
return nil;
}
NSData* keyData = [r dataNoCopyForColumnIndex: 0];
if (keyData.length != sizeof(TDBlobKey)) {
Warn(@"%@: Attachment %lld.'%@' has bogus key size %u",
self, sequence, filename, (unsigned)keyData.length);
*outStatus = kTDStatusCorruptError;
return nil;
}
filePath = [_attachments pathForKey: *(TDBlobKey*)keyData.bytes];
*outStatus = kTDStatusOK;
if (outType)
*outType = [r stringForColumnIndex: 1];
*outEncoding = [r intForColumnIndex: 2];
} @finally {
[r close];
}
return filePath;
}
/** Returns the content and MIME type of an attachment */
- (NSData*) getAttachmentForSequence: (SequenceNumber)sequence
named: (NSString*)filename
type: (NSString**)outType
encoding: (TDAttachmentEncoding*)outEncoding
status: (TDStatus*)outStatus
{
TDAttachmentEncoding encoding;
NSString* filePath = [self getAttachmentPathForSequence: sequence
named: filename
type: outType
encoding: &encoding
status: outStatus];
if (!filePath)
return nil;
NSError* error;
NSData* contents = [NSData dataWithContentsOfFile: filePath options: NSDataReadingMappedIfSafe
error: &error];
if (!contents) {
Warn(@"%@: Failed to load attachment %lld.'%@' -- %@", self, sequence, filename, error);
*outStatus = kTDStatusCorruptError;
return nil;
}
if (outEncoding)
*outEncoding = encoding;
else
contents = [self decodeAttachment: contents encoding: encoding];
return contents;
}
/** Constructs an "_attachments" dictionary for a revision, to be inserted in its JSON body. */
- (NSDictionary*) getAttachmentDictForSequence: (SequenceNumber)sequence
options: (TDContentOptions)options
{
Assert(sequence > 0);
FMResultSet* r = [_fmdb executeQuery:
@"SELECT filename, key, type, encoding, length, encoded_length, revpos "
"FROM attachments WHERE sequence=?",
@(sequence)];
if (!r)
return nil;
if (![r next]) {
[r close];
return nil;
}
BOOL decodeAttachments = !(options & kTDLeaveAttachmentsEncoded);
NSMutableDictionary* attachments = $mdict();
do {
NSData* keyData = [r dataNoCopyForColumnIndex: 1];
NSString* digestStr = [@"sha1-" stringByAppendingString: [TDBase64 encode: keyData]];
TDAttachmentEncoding encoding = [r intForColumnIndex: 3];
UInt64 length = [r longLongIntForColumnIndex: 4];
UInt64 encodedLength = [r longLongIntForColumnIndex: 5];
// Get the attachment contents if asked to:
NSData* data = nil;
BOOL dataSuppressed = NO;
if (options & kTDIncludeAttachments) {
UInt64 effectiveLength = (encoding && !decodeAttachments) ? encodedLength : length;
if ((options & kTDBigAttachmentsFollow) && effectiveLength >= kBigAttachmentLength) {
dataSuppressed = YES;
} else {
data = [_attachments blobForKey: *(TDBlobKey*)keyData.bytes];
if (!data)
Warn(@"TD_Database: Failed to get attachment for key %@", keyData);
}
}
NSString* encodingStr = nil;
id encodedLengthObj = nil;
if (encoding != kTDAttachmentEncodingNone) {
// Decode the attachment if it's included in the dict:
if (data && decodeAttachments) {
data = [self decodeAttachment: data encoding: encoding];
} else {
encodingStr = @"gzip"; // the only encoding I know
encodedLengthObj = @(encodedLength);
}
}
attachments[[r stringForColumnIndex: 0]] = $dict({@"stub", ((data || dataSuppressed) ? nil : $true)},
{@"data", (data ? [TDBase64 encode: data] : nil)},
{@"follows", (dataSuppressed ? $true : nil)},
{@"digest", digestStr},
{@"content_type", [r stringForColumnIndex: 2]},
{@"encoding", encodingStr},
{@"length", @(length)},
{@"encoded_length", encodedLengthObj},
{@"revpos", @([r intForColumnIndex: 6])});
} while ([r next]);
[r close];
return attachments;
}
- (NSURL*) fileForAttachmentDict: (NSDictionary*)attachmentDict
{
NSString* digest = attachmentDict[@"digest"];
if (![digest hasPrefix: @"sha1-"])
return nil;
NSData* keyData = [TDBase64 decode: [digest substringFromIndex: 5]];
if (!keyData)
return nil;
return [NSURL fileURLWithPath: [_attachments pathForKey: *(TDBlobKey*)keyData.bytes]];
}
// Calls the block on every attachment dictionary. The block can return a different dictionary,
// which will be replaced in the rev's properties. If it returns nil, the operation aborts.
// Returns YES if any changes were made.
+ (BOOL) mutateAttachmentsIn: (TD_Revision*)rev
withBlock: (NSDictionary*(^)(NSString*, NSDictionary*))block
{
NSDictionary* properties = rev.properties;
NSMutableDictionary* editedProperties = nil;
NSDictionary* attachments = (id)properties[@"_attachments"];
NSMutableDictionary* editedAttachments = nil;
for (NSString* name in attachments) {
@autoreleasepool {
NSDictionary* attachment = attachments[name];
NSDictionary* editedAttachment = block(name, attachment);
if (!editedAttachment) {
return NO; // block canceled
}
if (editedAttachment != attachment) {
if (!editedProperties) {
// Make the document properties and _attachments dictionary mutable:
editedProperties = [properties mutableCopy];
editedAttachments = [attachments mutableCopy];
editedProperties[@"_attachments"] = editedAttachments;
}
editedAttachments[name] = editedAttachment;
}
}
}
if (editedProperties) {
rev.properties = editedProperties;
return YES;
}
return NO;
}
// Replaces attachment data whose revpos is < minRevPos with stubs.
// If attachmentsFollow==YES, replaces data with "follows" key.
+ (void) stubOutAttachmentsIn: (TD_Revision*)rev
beforeRevPos: (int)minRevPos
attachmentsFollow: (BOOL)attachmentsFollow
{
if (minRevPos <= 1 && !attachmentsFollow)
return;
[self mutateAttachmentsIn: rev
withBlock: ^NSDictionary *(NSString *name, NSDictionary *attachment) {
int revPos = [attachment[@"revpos"] intValue];
bool includeAttachment = (revPos == 0 || revPos >= minRevPos);
bool stubItOut = !includeAttachment && !attachment[@"stub"];
bool addFollows = includeAttachment && attachmentsFollow
&& !attachment[@"follows"];
if (!stubItOut && !addFollows)
return attachment; // no change
// Need to modify attachment entry:
NSMutableDictionary* editedAttachment = [attachment mutableCopy];
[editedAttachment removeObjectForKey: @"data"];
if (stubItOut) {
// ...then remove the 'data' and 'follows' key:
[editedAttachment removeObjectForKey: @"follows"];
editedAttachment[@"stub"] = $true;
LogTo(SyncVerbose, @"Stubbed out attachment %@/'%@': revpos %d < %d",
rev, name, revPos, minRevPos);
} else if (addFollows) {
[editedAttachment removeObjectForKey: @"stub"];
editedAttachment[@"follows"] = $true;
LogTo(SyncVerbose, @"Added 'follows' for attachment %@/'%@': revpos %d >= %d",
rev, name, revPos, minRevPos);
}
return editedAttachment;
}];
}
// Replaces the "follows" key with the real attachment data in all attachments to 'doc'.
- (BOOL) inlineFollowingAttachmentsIn: (TD_Revision*)rev error: (NSError**)outError {
__block NSError *error = nil;
[[self class] mutateAttachmentsIn: rev
withBlock:
^NSDictionary *(NSString *name, NSDictionary *attachment) {
if (!attachment[@"follows"])
return attachment;
NSURL* fileURL = [self fileForAttachmentDict: attachment];
NSData* fileData = [NSData dataWithContentsOfURL: fileURL
options: NSDataReadingMappedIfSafe
error: &error];
if (!fileData)
return nil;
NSMutableDictionary* editedAttachment = [attachment mutableCopy];
[editedAttachment removeObjectForKey: @"follows"];
editedAttachment[@"data"] = [TDBase64 encode: fileData];
return editedAttachment;
}
];
if (outError)
*outError = error;
return (error == nil);
}
- (NSDictionary*) attachmentsFromRevision: (TD_Revision*)rev
status: (TDStatus*)outStatus
{
// If there are no attachments in the new rev, there's nothing to do:
NSDictionary* revAttachments = rev[@"_attachments"];
if (revAttachments.count == 0 || rev.deleted) {
*outStatus = kTDStatusOK;
return @{};
}
TDStatus status = kTDStatusOK;
NSMutableDictionary* attachments = $mdict();
for (NSString* name in revAttachments) {
// Create a TD_Attachment object:
NSDictionary* attachInfo = revAttachments[name];
NSString* contentType = $castIf(NSString, attachInfo[@"content_type"]);
TD_Attachment* attachment = [[TD_Attachment alloc] initWithName: name
contentType: contentType];
NSString* newContentsBase64 = $castIf(NSString, attachInfo[@"data"]);
if (newContentsBase64) {
// If there's inline attachment data, decode and store it:
@autoreleasepool {
NSData* newContents = [TDBase64 decode: newContentsBase64];
if (!newContents) {
status = kTDStatusBadEncoding;
break;
}
attachment->length = newContents.length;
if (![self storeBlob: newContents creatingKey: &attachment->blobKey]) {
status = kTDStatusAttachmentError;
break;
}
}
} else if ([attachInfo[@"follows"] isEqual: $true]) {
// "follows" means the uploader provided the attachment in a separate MIME part.
// This means it's already been registered in _pendingAttachmentsByDigest;
// I just need to look it up by its "digest" property and install it into the store:
status = [self installAttachment: attachment forInfo: attachInfo];
if (TDStatusIsError(status))
break;
} else {
// This item is just a stub; skip it
continue;
}
// Handle encoded attachment:
NSString* encodingStr = attachInfo[@"encoding"];
if (encodingStr) {
if ($equal(encodingStr, @"gzip"))
attachment->encoding = kTDAttachmentEncodingGZIP;
else {
status = kTDStatusBadEncoding;
break;
}
attachment->encodedLength = attachment->length;
attachment->length = $castIf(NSNumber, attachInfo[@"length"]).unsignedLongLongValue;
}
attachment->revpos = $castIf(NSNumber, attachInfo[@"revpos"]).unsignedIntValue;
attachments[name] = attachment;
}
*outStatus = status;
return status<300 ? attachments : nil;
}
- (TDStatus) processAttachments: (NSDictionary*)attachments
forRevision: (TD_Revision*)rev
withParentSequence: (SequenceNumber)parentSequence
{
Assert(rev);
// If there are no attachments in the new rev, there's nothing to do:
NSDictionary* revAttachments = rev[@"_attachments"];
if (revAttachments.count == 0 || rev.deleted)
return kTDStatusOK;
SequenceNumber newSequence = rev.sequence;
Assert(newSequence > 0);
Assert(newSequence > parentSequence);
unsigned generation = rev.generation;
Assert(generation > 0, @"Missing generation in rev %@", rev);
for (NSString* name in revAttachments) {
TDStatus status;
TD_Attachment* attachment = attachments[name];
if (attachment) {
// Determine the revpos, i.e. generation # this was added in. Usually this is
// implicit, but a rev being pulled in replication will have it set already.
if (attachment->revpos == 0)
attachment->revpos = generation;
else if (attachment->revpos > generation)
return kTDStatusBadAttachment;
// Finally insert the attachment:
status = [self insertAttachment: attachment forSequence: newSequence];
} else {
// It's just a stub, so copy the previous revision's attachment entry:
//? Should I enforce that the type and digest (if any) match?
status = [self copyAttachmentNamed: name
fromSequence: parentSequence
toSequence: newSequence];
}
if (TDStatusIsError(status))
return status;
}
return kTDStatusOK;
}
- (TDMultipartWriter*) multipartWriterForRevision: (TD_Revision*)rev
contentType: (NSString*)contentType
{
TDMultipartWriter* writer = [[TDMultipartWriter alloc] initWithContentType: contentType
boundary: nil];
[writer setNextPartsHeaders: @{@"Content-Type": @"application/json"}];
[writer addData: rev.asJSON];
NSDictionary* attachments = rev[@"_attachments"];
for (NSString* attachmentName in attachments) {
NSDictionary* attachment = attachments[attachmentName];
if (attachment[@"follows"]) {
NSString* disposition = $sprintf(@"attachment; filename=%@", TDQuoteString(attachmentName));
[writer setNextPartsHeaders: $dict({@"Content-Disposition", disposition})];
[writer addFileURL: [self fileForAttachmentDict: attachment]];
}
}
return writer;
}
- (TD_Revision*) updateAttachment: (NSString*)filename
body: (TDBlobStoreWriter*)body
type: (NSString*)contentType
encoding: (TDAttachmentEncoding)encoding
ofDocID: (NSString*)docID
revID: (NSString*)oldRevID
status: (TDStatus*)outStatus
{
*outStatus = kTDStatusBadAttachment;
if (filename.length == 0 || (body && !contentType) || (oldRevID && !docID) || (body && !docID))
return nil;
TD_Revision* oldRev = [[TD_Revision alloc] initWithDocID: docID
revID: oldRevID
deleted: NO];
if (oldRevID) {
// Load existing revision if this is a replacement:
*outStatus = [self loadRevisionBody: oldRev options: 0];
if (TDStatusIsError(*outStatus)) {
if (*outStatus == kTDStatusNotFound && [self existsDocumentWithID: docID revisionID: nil])
*outStatus = kTDStatusConflict; // if some other revision exists, it's a conflict
return nil;
}
} else {
// If this creates a new doc, it needs a body:
oldRev.body = [TD_Body bodyWithProperties: @{}];
}
// Update the _attachments dictionary:
NSMutableDictionary* attachments = [oldRev[@"_attachments"] mutableCopy];
if (!attachments)
attachments = $mdict();
if (body) {
TDBlobKey key = body.blobKey;
NSString* digest = [@"sha1-" stringByAppendingString: [TDBase64 encode: &key
length: sizeof(key)]];
[self rememberAttachmentWriter: body forDigest: digest];
NSString* encodingName = (encoding == kTDAttachmentEncodingGZIP) ? @"gzip" : nil;
attachments[filename] = $dict({@"digest", digest},
{@"length", @(body.length)},
{@"follows", $true},
{@"content_type", contentType},
{@"encoding", encodingName});
} else {
if (!attachments[filename]) {
*outStatus = kTDStatusAttachmentNotFound;
return nil;
}
[attachments removeObjectForKey: filename];
}
NSMutableDictionary* properties = [oldRev.properties mutableCopy];
properties[@"_attachments"] = attachments;
oldRev.properties = properties;
// Store a new revision with the updated _attachments:
TD_Revision* newRev = [self putRevision: oldRev prevRevisionID: oldRevID
allowConflict: NO status: outStatus];
if (!body && *outStatus == kTDStatusCreated)
*outStatus = kTDStatusOK;
return newRev;
}
- (TDStatus) garbageCollectAttachments {
// First delete attachment rows for already-cleared revisions:
// OPT: Could start after last sequence# we GC'd up to
[_fmdb executeUpdate: @"DELETE FROM attachments WHERE sequence IN "
"(SELECT sequence from revs WHERE json IS null)"];
// Now collect all remaining attachment IDs and tell the store to delete all but these:
FMResultSet* r = [_fmdb executeQuery: @"SELECT DISTINCT key FROM attachments"];
if (!r)
return kTDStatusDBError;
NSMutableSet* allKeys = [NSMutableSet set];
while ([r next]) {
[allKeys addObject: [r dataForColumnIndex: 0]];
}
[r close];
NSInteger numDeleted = [_attachments deleteBlobsExceptWithKeys: allKeys];
if (numDeleted < 0)
return kTDStatusAttachmentError;
Log(@"Deleted %d attachments", (int)numDeleted);
return kTDStatusOK;
}
@end