File: IMAPFolder.m

package info (click to toggle)
pantomime 1.1.2-3
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 2,224 kB
  • ctags: 389
  • sloc: objc: 15,433; ansic: 2,843; makefile: 75; sh: 4
file content (673 lines) | stat: -rw-r--r-- 15,736 bytes parent folder | download | duplicates (2)
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
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
/*
**  IMAPFolder.m
**
**  Copyright (c) 2001, 2002, 2003
**
**  Author: Ludovic Marcotte <ludovic@Sophos.ca>
**
**  This library is free software; you can redistribute it and/or
**  modify it under the terms of the GNU Lesser General Public
**  License as published by the Free Software Foundation; either
**  version 2.1 of the License, or (at your option) any later version.
**  
**  This library is distributed in the hope that it will be useful,
**  but WITHOUT ANY WARRANTY; without even the implied warranty of
**  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
**  Lesser General Public License for more details.
**  
**  You should have received a copy of the GNU Lesser General Public
**  License along with this library; if not, write to the Free Software
**  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/

#include <Pantomime/IMAPFolder.h>

#include <Pantomime/Connection.h>
#include <Pantomime/Constants.h>
#include <Pantomime/Flags.h>
#include <Pantomime/IMAPCacheManager.h>
#include <Pantomime/IMAPStore.h>
#include <Pantomime/IMAPMessage.h>
#include <Pantomime/TCPConnection.h>
#include <Pantomime/NSData+Extensions.h>
#include <Pantomime/NSString+Extensions.h>

#import <Foundation/NSAutoreleasePool.h>
#import <Foundation/NSDebug.h>
#import <Foundation/NSException.h>
#import <Foundation/NSScanner.h>

//
//
//
@implementation IMAPFolder

- (id) initWithName: (NSString *) theName
{
  self = [super initWithName: theName];
  
  [self setSelected: YES];
  [self setDelegate: nil];

  return self;
}


//
//
//
- (id) initWithName: (NSString *) theName
               mode: (int) theMode
{
  [self initWithName: theName];
  mode = theMode;

  return self;
}

//
//
//
- (void) dealloc
{
  DESTROY(delegate);

  [super dealloc];
}


//
//
//
- (void) appendMessageFromRawSource: (NSData *) theData
                              flags: (Flags *) theFlags
{
  NSString *flagsAsString;
  IMAPStore *aStore;
  NSData *aData;
 

  if ( theFlags )
    {
      flagsAsString = [self _flagsAsStringFromFlags: theFlags];
    }
  else
    {
      flagsAsString = @"";
    }
  
  // We remove any invalid headers from our message
  aData = [self _removeInvalidHeadersFromMessage: theData];

  // We obtain the pointer to our store
  aStore = (IMAPStore *)[self store];

  // We send our IMAP command
  [aStore _sendCommand: [NSString stringWithFormat: @"APPEND \"%@\" (%@) {%d}", // IMAP command
				  [[self name] modifiedUTF7String],             // folder name
				  flagsAsString,                                // flags
				  [aData length]]];                             // length of the data to write

  if ( aStore->_status.lastCommandWasSuccessful )
    {
      // We write our Message
      [[aStore tcpConnection] writeData: aData];
      
      // We send an empty line (just \r\n)
      [aStore _sendCommand: @""];
      
      // We read the responses from our IMAP server
      if ( !aStore->_status.lastCommandWasSuccessful )
	{
	  NSException *anException;
	  
	  NSDebugLog(@"IMAPFolder: APPEND failed to folder %@.", [self name]);
	  
	  anException = [NSException exceptionWithName: @"PantomimeFolderAppendMessageException"
				     reason: @""
				     userInfo: nil];
	  [anException raise];
	}
    }
  else
    {
      NSException *anException;
      
      NSDebugLog(@"IMAPFolder: APPEND failed to folder %@.", [self name]);
      
      anException = [NSException exceptionWithName: @"PantomimeFolderAppendMessageException"
				 reason: @""
				 userInfo: nil];
      [anException raise];
    }
}


//
// This method copies the messages in theMessages array FROM this folder
// to the destination folder's name, theFolder.
//
- (void) copyMessages: (NSArray *) theMessages
	     toFolder: (NSString *) theFolder
{
  NSMutableString *aMutableString;
  IMAPStore *aStore;
  int i;

  // We create our message's UID set
  aMutableString = [[NSMutableString alloc] init];

  for (i = 0; i < [theMessages count]; i++)
    {
      if (i == [theMessages count] - 1)
	{
	  [aMutableString appendFormat: @"%d", [[theMessages objectAtIndex: i] UID]];
	}
      else
	{
	  [aMutableString appendFormat: @"%d,", [[theMessages objectAtIndex: i] UID]];
	}
    }

  // We obtain the pointer to our store
  aStore = (IMAPStore *)[self store];
  
 
  // We send our IMAP command
  [aStore _sendCommand: [NSString stringWithFormat: @"UID COPY %@ \"%@\"",
				  aMutableString,
				  [theFolder modifiedUTF7String]]];
  RELEASE(aMutableString);

  if ( !aStore->_status.lastCommandWasSuccessful )
    {
      NSException *anException;
      
      NSDebugLog(@"IMAPFolder: COPY failed to folder %@.", theFolder);
      
      anException = [NSException exceptionWithName: @"PantomimeFolderCopyMessagesException"
				 reason: @""
				 userInfo: nil];
      [anException raise];
    }  
}


//
// This method is used to cache the messages from the IMAP server
// locally (in memory).
//
- (BOOL) prefetch
{
  int lastUID;

  lastUID = 0;
  
  // We first update the messages in our cache, if we need to.
  if ( [self cacheManager] )
    {
      NSArray *theCache;
      
      theCache = [[self cacheManager] cache];
      
      if ( [theCache count] > 0 ) 
	{
	  lastUID = [self _updateMessagesFromUID: [[theCache objectAtIndex: 0] UID]
			  toUID: [[theCache lastObject] UID] ];
	}
    }
  
  //
  // We must send this command since our IMAP cache might be empty (or have been removed).
  // In that case, we much fetch again all messages, starting at UID 1.
  //
  [(IMAPStore *)[self store] _sendCommand: [NSString stringWithFormat: @"UID FETCH %d:* (UID FLAGS RFC822.SIZE BODY.PEEK[HEADER.FIELDS (From To Cc Subject Date Message-ID References In-Reply-To MIME-Version)])", (lastUID+1)]];

   return YES;
}


//
// This method simply close the selected mailbox (ie. folder)
//
- (void) close
{
  DESTROY(delegate);

  if ( ![self selected])
    {
      return;
    }

  // We sync our cache manager if we have one
  if ( [self cacheManager] )
    {
      NSDebugLog(@"IMAPFolder: Synchronizing the IMAP cache manager...");
      [[self cacheManager] synchronize];
    }

  // We close the selected IMAP folder to _expunge_ messages marked as \Deleted
  // if and only we are NOT showing DELETED messages. We also don't send the command
  // if we are NOT connected since a MUA using Pantomime needs to call -close
  // on IMAPFolder to clean-up the "opened" folder.
  if ( ((IMAPStore *)[self store])->_status.connected && ![self showDeleted] )
    {
      [(IMAPStore *)[self store] _sendCommand: @"CLOSE"];
    }

  // We remove our current folder from the list of opened folders in the store.
  [(IMAPStore *)[self store] removeFolderFromOpenedFolders: self];
}


//
// This method returns all messages that have the flag DELETED.
// All the returned message ARE IN RAW SOURCE.
//
- (NSArray *) expunge: (BOOL) returnDeletedMessages
{
  NSMutableArray *aMutableArray;
  int i;

  aMutableArray = [[NSMutableArray alloc] init];

  for (i = 0; i < [allMessages count]; i++)
    {
      IMAPMessage *aMessage;
      
      aMessage = (IMAPMessage *)[allMessages objectAtIndex: i];
      
      // We add it to our array of returned message
      if ( [[aMessage flags] contain: DELETED] && returnDeletedMessages )
	{
	  [aMutableArray addObject: [aMessage rawSource]];
	}
    }

  //
  // We send our EXPUNGE command. The responses will be processed in IMAPStore and
  // the MSN will be updated in IMAPStore: -_parseExpunge.
  //
  [(IMAPStore *)[self store] _sendCommand: @"EXPUNGE"];

  if ([self cacheManager]) 
    {
      [[self cacheManager] synchronize];
    }
  
  return AUTORELEASE(aMutableArray);
}


//
//
//
- (int) UIDValidity
{
  return UIDValidity;
}


//
//
//
- (void) setUIDValidity: (int) theUIDValidity
{
  NSDebugLog(@"IMAPFolder: UIDVALIDITY = %d", theUIDValidity);
  UIDValidity = theUIDValidity;
}


//
//
//
- (BOOL) selected
{
  return selected;
}


//
//
//
- (void) setSelected: (BOOL) aBOOL
{
  selected = aBOOL;
}


//
//
//
- (void) setCacheManager: (id) theCacheManager
{
  [super setCacheManager: theCacheManager];

  if ( [[self cacheManager] UIDValidity] == 0 ||
       [[self cacheManager] UIDValidity] != [self UIDValidity] )
    {
      [[self cacheManager] flush];
      [[self cacheManager] setUIDValidity: [self UIDValidity]];
    }
}


//
//
//
- (id) delegate
{
  return delegate;
}


//
//
//
- (void) setDelegate: (id) theDelegate
{
  if ( theDelegate )
    {
      RETAIN(theDelegate);
      RELEASE(delegate);
      delegate = theDelegate;
    }
  else
    {
      DESTROY(delegate);
    }
}


//
//
//
- (void) setFlags: (Flags *) theFlags
         messages: (NSArray *) theMessages
{
  NSMutableString *aMutableString, *aSequenceSet;
  IMAPMessage *aMessage;

  if ( [theMessages count] == 1 )
    {
      aMessage = [theMessages lastObject];
      [[aMessage flags] replaceWithFlags: theFlags];
      aSequenceSet = [NSMutableString stringWithFormat: @"%d:%d",
				      [aMessage UID],
				      [aMessage UID]];
    }
  else
    {
      int i;

      aSequenceSet = [[NSMutableString alloc] init];

      for (i = 0; i < [theMessages count]; i++)
	{
	  aMessage = [theMessages objectAtIndex: i];
	  [[aMessage flags] replaceWithFlags: theFlags];

	  if ( aMessage == [theMessages lastObject] )
	    {
	      [aSequenceSet appendFormat: @"%d", [aMessage UID]];
	    }
	  else
	    {
	      [aSequenceSet appendFormat: @"%d,", [aMessage UID]];
	    }
	}
    }
  
  aMutableString = [[NSMutableString alloc] init];
  
  //
  // If we're removing all flags, we rather send a STORE -FLAGS (<current flags>) 
  // than a STORE FLAGS (<new flags>) since some broken servers might not 
  // support it (like Cyrus v1.5.19 and v1.6.24).
  //
  if ( theFlags->flags == 0 )
    {
      [aMutableString appendFormat: @"UID STORE %@ -FLAGS.SILENT (", aSequenceSet];
      [aMutableString appendString: [self _flagsAsStringFromFlags: theFlags]];
      [aMutableString appendString: @")"];
    }
  else
    {
      [aMutableString appendFormat: @"UID STORE %@ FLAGS.SILENT (", aSequenceSet];
      [aMutableString appendString: [self _flagsAsStringFromFlags: theFlags]];
      [aMutableString appendString: @")"];
    }
  
  [(IMAPStore *)[self store] _sendCommand: aMutableString];
  RELEASE(aMutableString);
}



//
// Using IMAP, we ignore most parameters.
//
- (NSArray *) search: (NSString *) theString
                mask: (int) theMask
             options: (int) theOptions
{
  IMAPStore *aStore;
  NSString *aString;
  
  // We obtain the pointer to our store and we remove all previous search results
  aStore = (IMAPStore *)[self store];
  [aStore->_status.searchResponse removeAllObjects];
 
  switch ( theMask )
    {
    case PantomimeFrom:
      aString = [NSString stringWithFormat: @"UID SEARCH ALL FROM \"%@\"", theString];
      break;
     
    case PantomimeTo:
      aString = [NSString stringWithFormat: @"UID SEARCH ALL TO \"%@\"", theString];
      break;

    case PantomimeContent:
      aString = [NSString stringWithFormat: @"UID SEARCH ALL BODY \"%@\"", theString];
      break;
      
    case PantomimeSubject:
    default:
      aString = [NSString stringWithFormat: @"UID SEARCH ALL SUBJECT \"%@\"", theString];
    }
  

  // We send our SEARCH command. Store->searchResponse will have the result.
  [aStore _sendCommand: aString];

  return [NSArray arrayWithArray: aStore->_status.searchResponse];
}

@end


//
// Private methods
// 
@implementation IMAPFolder (Private)

//
//
//
- (NSString *) _flagsAsStringFromFlags: (Flags *) theFlags
{
  NSMutableString *aMutableString;

  aMutableString = [[NSMutableString alloc] init];
  AUTORELEASE(aMutableString);

  if ( [theFlags contain: ANSWERED] )
    {
      [aMutableString appendString: @"\\Answered "];
    }

  if ( [theFlags contain: DRAFT] )
    {
      [aMutableString appendString: @"\\Draft "];
    }

  if ( [theFlags contain: FLAGGED] )
    {
      [aMutableString appendString: @"\\Flagged "];
    }

  if ( [theFlags contain: SEEN] )
    {
      [aMutableString appendString: @"\\Seen "];
    }
  
  if ( [theFlags contain: DELETED] )
    {
      [aMutableString appendString: @"\\Deleted "];
    }

  return [aMutableString stringByTrimmingWhiteSpaces];
}


//
//
//
- (NSData *) _removeInvalidHeadersFromMessage: (NSData *) theMessage
{
  NSMutableData *aMutableData;
  NSArray *allLines;
  int i;

  // We allocate our mutable data object
  aMutableData = [[NSMutableData alloc] initWithCapacity: [theMessage length]];
  
  // We now replace all \n by \r\n
  allLines = [theMessage componentsSeparatedByCString: "\n"];
  
  for (i = 0; i < [allLines count]; i++)
    {
      NSData *aLine;

      // We get a line...
      aLine = [allLines objectAtIndex: i];

      // We skip dumb headers
      if ( [aLine hasCPrefix: "From "] )
	{
	  continue;
	}

      [aMutableData appendData: aLine];
      [aMutableData appendCString: "\r\n"];
    }

  return AUTORELEASE(aMutableData);
}


//
// This methods updates all FLAGS and MSNs for messages in the cache.
//
// It also purges the messages that have been deleted on the IMAP server
// but that are still present in this cache.
// 
// It returns the last UID present in the cache.
//
// Nota bene: We can safely assume our cacheManager exists since this method
//            wouldn't otherwise have been invoked.
//
//
- (int) _updateMessagesFromUID: (int) startUID
			 toUID: (int) endUID
{
  NSMutableArray *theCache;
  IMAPMessage *aMessage;
  IMAPStore *aStore;

  int i, count, theUID;
  
  // We obtain our cache
  theCache = [[self cacheManager] cache];
  theUID = 0;

  
  //
  // Then, we send our IMAP command to update the FLAGS and the MSN of those messages.
  //
  aStore = (IMAPStore *)[self store];
  [aStore->_status.searchResponse removeAllObjects];
  [aStore _sendCommand: @"UID SEARCH 1:*"];
  
  //
  // We can now read our SEARCH results from our IMAP store. The result contains
  // all MSN->UID mappings. New messages weren't added to the search result as
  // we couldn't find them in IMAPStore: -_parseSearch:.
  //
  count = [aStore->_status.searchResponse count];

  for (i = 0; i < count; i++)
    {
      aMessage = [[self cacheManager] messageWithUID: [[aStore->_status.searchResponse objectAtIndex: i] UID]];
      
      if ( aMessage )
	{
	  [aMessage setFolder: self];
	  [aMessage setMessageNumber: (i+1)];
	}
    }

  //
  // We purge our cache from all deleted messages and we add the
  // good ones to our folder.
  //
  for (i = ([theCache count]-1); i >= 0; i--)
    {   
      aMessage = [theCache objectAtIndex: i];
      
      if ( [aMessage folder] == nil )
	{
	  //NSLog(@"REMOVING MESSAGE |%@| FROM CACHE", [aMessage subject]);
	  [theCache removeObject: aMessage]; 
	}
      
    }
  [self setMessages: theCache];
  
  
  //
  // We now update our \Answered flag, for all messages.
  //
  [aStore->_status.searchResponse removeAllObjects];
  [aStore _sendCommand: @"UID SEARCH ANSWERED"];
  count = [aStore->_status.searchResponse count];
  
  for (i = 0; i < count; i++)
    {
      [[[aStore->_status.searchResponse objectAtIndex: i] flags] add: ANSWERED];
    }

  //
  // We now update our \Seen flag, for all messages.
  //
  [aStore->_status.searchResponse removeAllObjects];
  [aStore _sendCommand: @"UID SEARCH UNSEEN"];
  count = [aStore->_status.searchResponse count];
  
  for (i = 0; i < count; i++)
    {
      [[[aStore->_status.searchResponse objectAtIndex: i] flags] remove: SEEN];
    }


  // We obtain the last UID of our cache and we synchronize it.
  // Messages will be fetched starting from that UID + 1.
  theUID = [[theCache lastObject] UID];   
  [[self cacheManager] synchronize];

  return theUID;
}

@end