/
UIxMailListActions.m
1024 lines (869 loc) · 31.1 KB
/
UIxMailListActions.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
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright (C) 2006-2015 Inverse inc.
This file is part of SOGo
SOGo 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, or (at your option) any
later version.
SOGo 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 SOGo; see the file COPYING. If not, write to the
Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA.
*/
/*
UIxMailListActions
This component represent a list of mails and is attached to an SOGoMailFolder
object.
*/
#import <Foundation/NSCalendarDate.h>
#import <Foundation/NSCharacterSet.h>
#import <Foundation/NSTimeZone.h>
#import <Foundation/NSUserDefaults.h> /* for locale string constants */
#import <Foundation/NSValue.h>
#import <NGObjWeb/WOApplication.h>
#import <NGObjWeb/WOContext+SoObjects.h>
#import <NGObjWeb/WORequest.h>
#import <NGObjWeb/SoObject+SoDAV.h>
#import <NGObjWeb/NSException+HTTP.h>
#import <NGExtensions/NSNull+misc.h>
#import <NGExtensions/NSString+misc.h>
#import <NGExtensions/NSObject+Logs.h>
#import <NGImap4/NGImap4Connection.h>
#import <NGImap4/NGImap4Envelope.h>
#import <EOControl/EOQualifier.h>
#import <Mailer/NSString+Mail.h>
#import <Mailer/SOGoDraftsFolder.h>
#import <Mailer/SOGoMailAccount.h>
#import <Mailer/SOGoSentFolder.h>
#import <SOGo/NSArray+Utilities.h>
#import <SOGo/NSDictionary+Utilities.h>
#import <SOGo/NSObject+Utilities.h>
#import <SOGo/NSString+Utilities.h>
#import <SOGo/SOGoDateFormatter.h>
#import <SOGo/SOGoUser.h>
#import <SOGo/SOGoUserDefaults.h>
#import <SOGo/SOGoUserSettings.h>
#import <SOGo/WOResourceManager+SOGo.h>
#import <UI/MailPartViewers/UIxMailSizeFormatter.h>
#import "WOContext+UIxMailer.h"
#import "UIxMailFormatter.h"
#import "UIxMailListActions.h"
// The maximum number of headers to prefetch when querying the UIDs list
#define headersPrefetchMaxSize 100
@implementation UIxMailListActions
- (id) initWithRequest: (WORequest *) newRequest
{
SOGoUser *user;
if ((self = [super initWithRequest: newRequest]))
{
user = [[self context] activeUser];
ASSIGN (now, [NSCalendarDate calendarDate]);
ASSIGN (dateFormatter, [user dateFormatterInContext: context]);
ASSIGN (userTimeZone, [[user userDefaults] timeZone]);
[now setTimeZone: userTimeZone];
sortByThread = [[user userDefaults] mailSortByThreads];
folderType = 0;
specificMessageNumber = 0;
}
return self;
}
- (void) dealloc
{
[sortedUIDs release];
[messages release];
[message release];
[dateFormatter release];
[userTimeZone release];
[super dealloc];
}
/* accessors */
- (void) setMessage: (id) _msg
{
ASSIGN (message, _msg);
}
- (id) message
{
return message;
}
- (NSString *) messageDate
{
NSCalendarDate *messageDate;
messageDate = [[message valueForKey: @"envelope"] date];
[messageDate setTimeZone: userTimeZone];
if ([now dayOfCommonEra] == [messageDate dayOfCommonEra])
{
// Same day
return [dateFormatter formattedTime: messageDate];
}
else if ([now dayOfCommonEra] - [messageDate dayOfCommonEra] == 1)
{
// Yesterday
return [NSString stringWithFormat: @"%@ %@",
[self labelForKey: @"Yesterday" inContext: context],
[dateFormatter formattedTime: messageDate]];
}
else if ([now dayOfCommonEra] - [messageDate dayOfCommonEra] < 7)
{
// Same week
return [NSString stringWithFormat: @"%@ %@",
[[locale objectForKey: NSWeekDayNameArray] objectAtIndex: [messageDate dayOfWeek]],
[dateFormatter formattedTime: messageDate]];
}
else
{
return [dateFormatter shortFormattedDate: messageDate];
}
}
- (UIxMailSizeFormatter *) sizeFormatter
{
return [UIxMailSizeFormatter sharedMailSizeFormatter];
}
//
// Priorities are defined like this:
//
// X-Priority: 1 (Highest)
// X-Priority: 2 (High)
// X-Priority: 3 (Normal)
// X-Priority: 4 (Low)
// X-Priority: 5 (Lowest)
//
// Sometimes, the MUAs don't send over the string in () so we ignore it.
//
- (NSDictionary *) messagePriority
{
NSUInteger priority;
NSString *description;
NSData *data;
data = [message objectForKey: @"header"];
priority = 3;
description = [self labelForKey: @"normal" inContext: context];
if (data)
{
NSString *s;
s = [[NSString alloc] initWithData: data
encoding: NSASCIIStringEncoding];
if (s)
{
NSRange r;
[s autorelease];
r = [s rangeOfString: @":"];
if (r.length)
{
s = [[s substringFromIndex: r.location+1]
stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
if ([s hasPrefix: @"1"])
{
priority = 1;
description = [self labelForKey: @"highest" inContext: context];
}
else if ([s hasPrefix: @"2"])
{
priority = 2;
description = [self labelForKey: @"high" inContext: context];
}
else if ([s hasPrefix: @"4"])
{
priority = 4;
description = [self labelForKey: @"low" inContext: context];
}
else if ([s hasPrefix: @"5"])
{
priority = 5;
description = [self labelForKey: @"lowest" inContext: context];
}
}
}
}
return [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt: priority], @"level",
description, @"name",
nil];
}
- (NSString *) messageSubject
{
id baseSubject;
NSString *subject;
baseSubject = [[message valueForKey: @"envelope"] subject];
subject = [baseSubject decodedHeader];
if (![subject length])
subject = @"";
// NSLog(@"*** subject = |%@|", subject);
return subject;
}
- (BOOL) showToAddress
{
SOGoMailFolder *co;
if (!folderType)
{
co = [self clientObject];
if ([co isKindOfClass: [SOGoSentFolder class]]
|| [co isKindOfClass: [SOGoDraftsFolder class]])
folderType = 1;
else
folderType = -1;
}
return (folderType == 1);
}
/* title */
- (NSString *) objectTitle
{
return [[self clientObject] nameInContainer];
}
- (NSString *) panelTitle
{
NSString *s;
s = [self labelForKey:@"View Mail Folder" inContext: context];
s = [s stringByAppendingString:@": "];
s = [s stringByAppendingString:[self objectTitle]];
return s;
}
/* derived accessors */
- (BOOL) isMessageDeleted
{
NSArray *flags;
flags = [[self message] valueForKey: @"flags"];
return [flags containsObject: @"deleted"];
}
- (BOOL) isMessageRead
{
NSArray *flags;
flags = [[self message] valueForKey: @"flags"];
return [flags containsObject: @"seen"];
}
- (BOOL) isMessageFlagged
{
NSArray *flags;
flags = [[self message] valueForKey: @"flags"];
return [flags containsObject: @"flagged"];
}
- (BOOL) isMessageAnswered
{
NSArray *flags;
flags = [[self message] valueForKey: @"flags"];
return [flags containsObject: @"answered"];
}
- (BOOL) isMessageForwarded
{
NSArray *flags;
flags = [[self message] valueForKey: @"flags"];
return [flags containsObject: @"$forwarded"];
}
- (NSString *) messageUidString
{
return [[[self message] valueForKey:@"uid"] stringValue];
}
- (BOOL) hasMessageAttachment
{
NSArray *parts;
NSEnumerator *dispositions;
NSDictionary *currentDisp;
BOOL hasAttachment;
hasAttachment = NO;
parts = [[message objectForKey: @"bodystructure"] objectForKey: @"parts"];
if ([parts count] > 1)
{
dispositions = [[parts objectsForKey: @"disposition"
notFoundMarker: nil] objectEnumerator];
while (!hasAttachment
&& (currentDisp = [dispositions nextObject]))
hasAttachment = ([[currentDisp objectForKey: @"type"] length]);
}
return hasAttachment;
}
/* fetching messages */
- (NSArray *) fetchKeys
{
/* Note: see SOGoMailManager.m for allowed IMAP4 keys */
static NSArray *keys = nil;
if (!keys)
keys = [[NSArray alloc] initWithObjects: @"UID",
@"FLAGS", @"ENVELOPE", @"RFC822.SIZE",
@"BODYSTRUCTURE", @"BODY.PEEK[HEADER.FIELDS (X-PRIORITY)]", nil];
return keys;
}
- (NSString *) defaultSortKey
{
return @"ARRIVAL";
}
- (NSString *) imap4SortOrdering
{
WORequest *request;
NSString *sort, *module;
NSMutableDictionary *moduleSettings;
NSDictionary *urlParams, *sortingAttributes;
SOGoUser *activeUser;
SOGoUserSettings *us;
BOOL asc, dry;
request = [context request];
urlParams = [[request contentAsString] objectFromJSONString];
sortingAttributes = [urlParams objectForKey: @"sortingAttributes"];
sort = [[sortingAttributes objectForKey: @"sort"] uppercaseString];
asc = [[sortingAttributes objectForKey: @"asc"] boolValue];
dry = [[sortingAttributes objectForKey: @"dry"] boolValue];
activeUser = [context activeUser];
module = @"Mail";
us = [activeUser userSettings];
moduleSettings = [us objectForKey: module];
if ([sort length])
{
if ([sort isEqualToString: [self defaultSortKey]] && !asc)
{
if (moduleSettings && !dry)
{
[moduleSettings removeObjectForKey: @"SortingState"];
[us synchronize];
}
}
else if (!dry)
{
// Save the sorting state in the user settings
if (!moduleSettings)
{
moduleSettings = [NSMutableDictionary dictionary];
[us setObject: moduleSettings forKey: module];
}
[moduleSettings setObject: [NSArray arrayWithObjects: [sort lowercaseString], [NSString stringWithFormat: @"%d", (asc ? 1 : 0)], nil]
forKey: @"SortingState"];
[us synchronize];
}
}
else if (moduleSettings)
{
NSArray *sortState = [moduleSettings objectForKey: @"SortingState"];
if ([sortState count])
{
sort = [[sortState objectAtIndex: 0] uppercaseString];
asc = [[sortState objectAtIndex: 1] boolValue];
}
}
if (![sort length])
sort = [self defaultSortKey];
// Construct and return the final IMAP ordering constraint
if (!asc)
sort = [@"REVERSE " stringByAppendingString: sort];
return sort;
}
- (EOQualifier *) searchQualifier
{
EOQualifier *qualifier, *searchQualifier;
WORequest *request;
NSDictionary *sortingAttributes, *content, *filter;
NSArray *filters;
NSString *searchBy, *searchInput, *searchString, *match;
NSMutableArray *searchArray;
int nbFilters, i;
request = [context request];
content = [[request contentAsString] objectFromJSONString];
qualifier = nil;
searchString = nil;
match = nil;
filters = [content objectForKey: @"filters"];
if (filters)
{
nbFilters = [filters count];
if (nbFilters > 0) {
searchArray = [NSMutableArray arrayWithCapacity: nbFilters];
sortingAttributes = [content objectForKey: @"sortingAttributes"];
if (sortingAttributes)
match = [sortingAttributes objectForKey: @"match"]; // AND, OR
for (i = 0; i < nbFilters; i++)
{
filter = [filters objectAtIndex:i];
searchBy = [filter objectForKey: @"searchBy"];
searchInput = [filter objectForKey: @"searchInput"];
if (searchBy && searchInput)
{
if ([[filter objectForKey: @"negative"] boolValue])
searchString = [NSString stringWithFormat: @"(not (%@ doesContain: '%@'))", searchBy, searchInput];
else
searchString = [NSString stringWithFormat: @"(%@ doesContain: '%@')", searchBy, searchInput];
searchQualifier = [EOQualifier qualifierWithQualifierFormat: searchString];
if (searchQualifier)
[searchArray addObject: searchQualifier];
}
else
{
[self errorWithFormat: @"Missing parameters in search filter: %@", filter];
}
}
if ([match isEqualToString: @"OR"])
qualifier = [[EOOrQualifier alloc] initWithQualifierArray: searchArray];
else
qualifier = [[EOAndQualifier alloc] initWithQualifierArray: searchArray];
}
}
return qualifier;
}
- (NSArray *) getSortedUIDsInFolder: (SOGoMailFolder *) mailFolder
{
EOQualifier *qualifier, *fetchQualifier, *notDeleted;
if (!sortedUIDs)
{
notDeleted = [EOQualifier qualifierWithQualifierFormat: @"(not (flags = %@))", @"deleted"];
qualifier = [self searchQualifier];
if (qualifier)
{
fetchQualifier = [[EOAndQualifier alloc] initWithQualifiers: notDeleted, qualifier, nil];
[fetchQualifier autorelease];
}
else
fetchQualifier = notDeleted;
sortedUIDs = [mailFolder fetchUIDsMatchingQualifier: fetchQualifier
sortOrdering: [self imap4SortOrdering]
threaded: sortByThread];
[sortedUIDs retain];
}
return sortedUIDs;
}
/**
* Returns the messages threads as triples of
* metadata, including the message UID, thread level and root position.
* @param _sortedUIDs the interleaved arrays representation of the messages UIDs
* @return an flatten array representation of the messages UIDs
*/
- (NSArray *) threadedUIDs: (NSArray *) _sortedUIDs
{
NSMutableArray *threads;
NSMutableArray *currentThreads;
NSEnumerator *rootThreads;
id thread;
int count;
int i;
BOOL first;
BOOL expected;
i = 0;
expected = YES;
threads = [NSMutableArray arrayWithObject: [NSArray arrayWithObjects: @"uid", @"level", @"first", nil]];
rootThreads = [_sortedUIDs objectEnumerator];
thread = [rootThreads nextObject];
// Make sure rootThreads starts with an NSArray
if (![thread respondsToSelector: @selector(objectEnumerator)])
return nil;
count = 0;
first = [thread count] > 1;
thread = [thread objectEnumerator];
currentThreads = [NSMutableArray array];
while (thread)
{
unsigned int ecount = 0;
id t;
if ([thread isKindOfClass: [NSEnumerator class]])
{
t = [thread nextObject];
}
else
t = thread; // never happen?
while (t && ![t isKindOfClass: [NSArray class]])
{
int level;
NSArray *currentThread;
level = first? 0 : (count > 0? count : -1);
currentThread = [NSArray arrayWithObjects: t,
[NSNumber numberWithInt: level],
[NSNumber numberWithInt: first], nil];
[threads addObject: currentThread];
i++;
count++;
ecount++;
expected = NO;
t = [thread nextObject];
first = 0;
}
if (t)
{
// If t is defined, it has to be an NSArray
if (expected)
{
count++;
expected = NO;
}
thread = [thread allObjects];
if ([thread count] > 0)
[currentThreads addObject: [thread objectEnumerator]];
thread = [t objectEnumerator];
}
else if ([currentThreads count] > 0)
{
thread = [currentThreads objectAtIndex: 0];
[currentThreads removeObjectAtIndex: 0];
count -= ecount;
}
else
{
thread = [rootThreads nextObject];
count = 0;
first = [thread count] > 1;
thread = [thread objectEnumerator];
expected = YES;
}
// Prepare next iteration
thread = [thread allObjects];
thread = [thread objectEnumerator];
}
return threads;
}
- (int) indexOfMessageUID: (int) messageNbr
{
NSArray *messageNbrs;
int index;
messageNbrs = [self getSortedUIDsInFolder: [self clientObject]];
index
= [messageNbrs indexOfObject: [NSNumber numberWithInt: messageNbr]];
// if (index < 0)
// index = 0;
return index;
}
/* error redirects */
/*
- (id) redirectToViewWithError: (id) _error
{
// TODO: DUP in UIxMailAccountView
// TODO: improve, localize
// TODO: there is a bug in the treeview which preserves the current URL for
// the active object (displaying the error again)
id url;
if (![_error isNotNull])
return [self redirectToLocation:@"view"];
if ([_error isKindOfClass:[NSException class]])
_error = [_error reason];
else if ([_error isKindOfClass:[NSString class]])
_error = [_error stringValue];
url = [_error stringByEscapingURL];
url = [@"view?error=" stringByAppendingString:url];
return [self redirectToLocation:url];
}
*/
- (NSDictionary *) getUIDsInFolder: (SOGoMailFolder *) folder
withHeaders: (BOOL) includeHeaders
{
NSArray *uids, *threadedUids, *headers;
NSMutableDictionary *data;
SOGoMailAccount *account;
id quota;
NSRange r;
int count;
data = [NSMutableDictionary dictionary];
// TODO: we might want to flush the caches?
//[folder flushMailCaches];
[folder expungeLastMarkedFolder];
// Retrieve messages UIDs using form parameters "sort" and "asc"
uids = [self getSortedUIDsInFolder: folder];
if (uids == nil)
{
[folder unsubscribe]; // Mailbox is possibly missing -- cleanup subscriptions
return nil;
}
// We first make sure QRESYNC is enabled
if (![[folder imap4Connection] enableExtensions: [NSArray arrayWithObject: @"QRESYNC"]])
{
NSString *tag = [folder davCollectionTag];
if (![tag isEqualToString: @"-1"])
{
[data setObject: tag forKey: @"syncToken"];
}
}
// Get rid of the extra parenthesis
// uids = [[[[uids stringValue] stringByReplacingOccurrencesOfString:@"(" withString:@""] stringByReplacingOccurrencesOfString:@")" withString:@""] componentsSeparatedByString:@","];
if (includeHeaders)
{
// Also retrieve the first headers, up to 'headersPrefetchMaxSize'
NSArray *a;
a = [uids flattenedArray];
count = [a count];
if (count > headersPrefetchMaxSize)
count = headersPrefetchMaxSize;
r = NSMakeRange(0, count);
headers = [self getHeadersForUIDs: [a subarrayWithRange: r]
inFolder: folder];
[data setObject: headers forKey: @"headers"];
}
if (sortByThread)
{
// Add threads information
threadedUids = [self threadedUIDs: uids];
if (threadedUids != nil)
uids = threadedUids;
else
sortByThread = NO;
}
if (uids != nil)
[data setObject: uids forKey: @"uids"];
[data setObject: [NSNumber numberWithBool: sortByThread] forKey: @"threaded"];
// We get the unseen count
[data setObject: [NSNumber numberWithUnsignedInt: [folder unseenCount]] forKey: @"unseenCount"];
// We also return the inbox quota
account = [folder mailAccountFolder];
quota = [account getInboxQuota];
if (quota != nil)
[data setObject: quota forKey: @"quotas"];
return data;
}
/* Module actions */
/**
* @api {get} /so/:username/Mail/:accountId/:mailboxPath/view List messages UIDs
* @apiVersion 1.0.0
* @apiName GetMailUIDsList
* @apiGroup Mail
* @apiExample {curl} Example usage:
* curl -i http://localhost/SOGo/so/sogo1/Mail/0/folderINBOX/view
* -H 'Content-Type: application/json' \
* -d '{ "sortingAttributes": { "match": "AND", "asc": true, "sort": "subject" }, \
* "filters": [{ "searchBy": "subject", "searchInput": "foo" }] }'
*
* @apiParam {Object} [sortingAttributes] Sorting preferences
* @apiParam {Boolean} [sortingAttributes.asc] Descending sort when false. Defaults to true (ascending).
* @apiParam {String} [sortingAttributes.sort] Sort field. Either c_cn, c_mail, c_screenname, c_o, or c_telephonenumber.
* @apiParam {String} [sortingAttributes.match] Either OR or AND.
* @apiParam {String} [sortingAttributes.noHeaders] Don't send the headers if true. Defaults to false.
* @apiParam {Object[]} [filters] The filters to apply.
* @apiParam {String} filters.searchBy Field criteria. Either subject, from, to, cc, or body.
* @apiParam {String} filters.searchInput String to match.
* @apiParam {String} [filters.negative] Reverse the condition when true. Defaults to false.
*
* @apiSuccess (Success 200) {Number} threaded 1 if threading is enabled for the user.
* @apiSuccess (Success 200) {Number} unseenCount Number of unread messages
* @apiSuccess (Success 200) {Number[]} uids List of uids matching the filters, in the requested order.
* @apiSuccess (Success 200) {String[]} headers The first entry are the fields names.
* @apiSuccess (Success 200) {Object[]} headers.To Recipients
* @apiSuccess (Success 200) {String} headers.To.name Recipient's name
* @apiSuccess (Success 200) {String} headers.To.email Recipient's email address
* @apiSuccess (Success 200) {Number} headers.hasAttachment 1 when there is at least one attachment
* @apiSuccess (Success 200) {Number} headers.isFlagged 1 if the message is flagged
* @apiSuccess (Success 200) {String} headers.Subject Subject
* @apiSuccess (Success 200) {Object[]} headers.From Senders
* @apiSuccess (Success 200) {String} headers.From.name Sender's name
* @apiSuccess (Success 200) {String} headers.From.email Sender's email address
* @apiSuccess (Success 200) {Number} headers.isRead 1 if message is read
* @apiSuccess (Success 200) {String} headers.Priority Priority
* @apiSuccess (Success 200) {String} headers.Priority.level Priority number
* @apiSuccess (Success 200) {String} headers.Priority.name Priority description
* @apiSuccess (Success 200) {String} headers.RelativeDate Message date relative to now
* @apiSuccess (Success 200) {String} headers.Size Formatted message size
* @apiSuccess (Success 200) {String[]} headers.Flags Flags, such as "answered" and "seen"
* @apiSuccess (Success 200) {Number} headers.uid Message UID
* @apiSuccess (Success 200) {Object} [quotas] Quota information
* @apiSuccess (Success 200) {Number} [quotas.usedSpace] Used space
* @apiSuccess (Success 200) {Number} [quotas.maxQuota] Mailbox maximum quota
*/
- (id <WOActionResults>) getUIDsAction
{
BOOL noHeaders;
NSDictionary *data, *requestContent;
SOGoMailFolder *folder;
WORequest *request;
WOResponse *response;
request = [context request];
requestContent = [[request contentAsString] objectFromJSONString];
folder = [self clientObject];
noHeaders = [[[requestContent objectForKey: @"sortingAttributes"] objectForKey: @"noHeaders"] boolValue];
data = [self getUIDsInFolder: folder
withHeaders: !noHeaders];
if (data != nil)
response = [self responseWithStatus: 200 andJSONRepresentation: data];
else if ([folder isSpecialFolder])
{
response = [self responseWithStatus: 204];
}
else
{
data = [NSDictionary dictionaryWithObjectsAndKeys:
@"An error occured while communicating with the mail server", @"message", nil];
response = [self responseWithStatus: 500 /* Error */
andJSONRepresentation: data];
}
return response;
}
- (id <WOActionResults>) getChangesAction
{
NSArray *changedMessages, *headers;
NSDictionary *requestContent, *data, *changedMessage;
NSMutableArray *changedUids, *deletedUids;
NSString *syncToken, *newSyncToken, *uid;
SOGoMailFolder *folder;
WORequest *request;
WOResponse *response;
int i, max;
request = [context request];
requestContent = [[request contentAsString] objectFromJSONString];
response = nil;
folder = [self clientObject];
syncToken = [requestContent objectForKey: @"syncToken"];
newSyncToken = [folder davCollectionTag];
if ([syncToken length] && ![syncToken isEqual: newSyncToken])
{
// Fetch list of changed uids
changedMessages = [folder syncTokenFieldsWithProperties: nil
matchingSyncToken: syncToken
fromDate: nil
initialLoad: NO
sortOrdering: [self imap4SortOrdering]
threaded: sortByThread];
if ((max = [changedMessages count]))
{
// Split new or modified uids from deleted uids
changedUids = [NSMutableArray array];
deletedUids = [NSMutableArray array];
for (i = 0; i < max; i++)
{
changedMessage = [changedMessages objectAtIndex: i];
uid = [[changedMessage allKeys] lastObject];
if ([[changedMessage objectForKey: uid] isEqual: [NSNull null]])
[deletedUids addObject: uid];
else
[changedUids addObject: uid];
}
// Fetch headers for new or modified messages
headers = [self getHeadersForUIDs: changedUids
inFolder: folder];
data = [NSDictionary dictionaryWithObjectsAndKeys:
changedUids, @"changed",
deletedUids, @"deleted",
headers, @"headers",
newSyncToken, @"syncToken",
nil];
response = [self responseWithStatus: 200 andJSONRepresentation: data];
}
}
if (!response)
{
data = [NSDictionary dictionaryWithObjectsAndKeys:
newSyncToken, @"syncToken",
nil];
response = [self responseWithStatus: 200 andJSONRepresentation: data];
}
return response;
}
- (NSArray *) getHeadersForUIDs: (NSArray *) uids
inFolder: (SOGoMailFolder *) mailFolder
{
UIxEnvelopeAddressFormatter *addressFormatter;
NSMutableArray *headers, *msg, *tags;
NSEnumerator *msgsList;
NSArray *to, *from;
NSDictionary *msgs;
NSString *msgDate;
int count;
count = [uids count];
headers = [NSMutableArray arrayWithCapacity: count];
if (count > 0)
{
addressFormatter = [context mailEnvelopeAddressFormatter];
// Fetch headers
msgs = (NSDictionary *)[mailFolder fetchUIDs: uids
parts: [self fetchKeys]];
msgsList = [[msgs objectForKey: @"fetch"] objectEnumerator];
[self setMessage: [msgsList nextObject]];
msg = [NSMutableArray arrayWithObjects: @"To", @"hasAttachment", @"isFlagged", @"Subject", @"From", @"isRead", @"Priority", @"RelativeDate", @"Size", @"Flags", @"uid", @"isAnswered", @"isForwarded", nil];
[headers addObject: msg];
while (message)
{
// We must check for "umimportant" untagged responses.
//
// It's generally caused by IMAP server processes sending untagged IMAP responses to SOGo in differnent IMAP
// connections (SOGo might use 2-3 per user). Say you ask your messages:
//
// 127.000.000.001.40725-127.000.000.001.00143: 59 uid fetch 62 (UID FLAGS ENVELOPE RFC822.SIZE BODYSTRUCTURE BODY.PEEK[HEADER.FIELDS (X-PRIORITY)])
// 127.000.000.001.00143-127.000.000.001.40725: * 62 FETCH (UID 62 FLAGS (\Seen) RFC822.SIZE 854 ENVELOPE .... (
// * 61 FETCH (FLAGS (\Deleted \Seen))
// * 62 FETCH (FLAGS (\Deleted \Seen))
// * 63 FETCH (FLAGS (\Deleted \Seen))
// 59 OK Fetch completed.
//
// We must ignore the * 61 .. * 63 untagged responses.
//
if (![message objectForKey: @"uid"])
{
[self setMessage: [msgsList nextObject]];
continue;
}
msg = [NSMutableArray arrayWithCapacity: 12];
// Columns data
// To
to = [[message objectForKey: @"envelope"] to];
if ([to count] > 0)
[msg addObject: [addressFormatter dictionariesForArray: to]];
else
[msg addObject: @""];
// hasAttachment
[msg addObject: [NSNumber numberWithBool: [self hasMessageAttachment]]];
// isFlagged
[msg addObject: [NSNumber numberWithBool: [self isMessageFlagged]]];
// Subject
[msg addObject: [self messageSubject]];
// From
from = [[message objectForKey: @"envelope"] from];
if ([from count] > 0)
[msg addObject: [addressFormatter dictionariesForArray: from]];
else
[msg addObject: @""];
// isRead
[msg addObject: [NSNumber numberWithBool: [self isMessageRead]]];
// Priority
[msg addObject: [self messagePriority]];
// Relative Date
msgDate = [self messageDate];
if (msgDate == nil)
msgDate = @"";
[msg addObject: msgDate];
// Size
[msg addObject: [[self sizeFormatter] stringForObjectValue: [message objectForKey: @"size"]]];
// Mail labels / tags
tags = [NSMutableArray arrayWithArray: [message objectForKey: @"flags"]];
[tags removeObject: @"answered"];
[tags removeObject: @"deleted"];
[tags removeObject: @"draft"];
[tags removeObject: @"flagged"];
[tags removeObject: @"recent"];
[tags removeObject: @"seen"];
[tags removeObject: @"$forwarded"];
[msg addObject: tags];
// UID
[msg addObject: [message objectForKey: @"uid"]];
[headers addObject: msg];
// isAnswered
[msg addObject: [NSNumber numberWithBool: [self isMessageAnswered]]];
// isForwarded
[msg addObject: [NSNumber numberWithBool: [self isMessageForwarded]]];
[self setMessage: [msgsList nextObject]];
}
}
return headers;
}
- (id <WOActionResults>) getHeadersAction
{
NSArray *uids, *headers;
NSDictionary *data;
WORequest *request;
WOResponse *response;
request = [context request];
data = [[request contentAsString] objectFromJSONString];
if (![[data objectForKey: @"uids"] isKindOfClass: [NSArray class]]
|| [[data objectForKey: @"uids"] count] == 0)
{
data = [NSDictionary dictionaryWithObjectsAndKeys:
@"No UID specified", @"message", nil];
response = [self responseWithStatus: 404 /* Not Found */
andJSONRepresentation: data];