File: mailfolder.cpp

package info (click to toggle)
aethera 0.9.3-7
  • links: PTS
  • area: main
  • in suites: woody
  • size: 8,588 kB
  • ctags: 7,282
  • sloc: cpp: 64,544; sh: 9,913; perl: 1,756; makefile: 1,680; python: 258
file content (735 lines) | stat: -rw-r--r-- 17,524 bytes parent folder | download
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
/***************************************************************************
                          mailfolder.cpp  -  the mail folder interface
                             -------------------
    begin                : Mon Mar  5 16:16:00 EET 2001
    copyright            : (C) 2001 by theKompany (www.thekompany.com>
    author               : Eugen Constantinescu
    email                : eug@thekompany.com
 ***************************************************************************/

#include <config.h>
#include <mailfolder.h>
#include <qdir.h>
#include <qfile.h>
#include <indexclass.h>
#include <qtextstream.h>
#include <servernotifier.h>
#include <kconfig.h>
#include <accounts.h>
#include <accountmanager.h>
#include <messagedevice.h>
#include <messagedescriptor.h>
#include <messagefactory.h>
#include <mimecodec.h>

unsigned long MailFolder::lastIndexID;
QList<class MailFolder> MailFolder::folderList;
bool MailFolder::autoExpunge=true;

extern KConfig *GlobalConfig;

MailFolder::MailFolder(const QString &_storageDevice)
{
	folderList.append(this);
	
	storageDevice=_storageDevice;
	setupFiles();
};

MailFolder::~MailFolder()
{
	folderList.removeRef(this);
}

void MailFolder::setupFiles()
{
	indexFileName=storageDevice+"/index";
	descriptorFileName=storageDevice+"/descriptor";

	if(storageDevice.contains("sysmail_deleted"))
	{
		folderType=MailFolder::Deleted;
    messagesPlace=MailFolder::LOCAL;
    folderProtocol=MailFolder::MBOX;
    accessRights=MailFolder::ALL;
	}
	else if(storageDevice.contains("sysmail_drafts"))
	{
		folderType=MailFolder::Drafts;
    messagesPlace=MailFolder::LOCAL;
    folderProtocol=MailFolder::MBOX;
    accessRights=MailFolder::ALL;
	}
	else if(storageDevice.contains("sysmail_inbox"))
	{
		folderType=MailFolder::Inbox;
    messagesPlace=MailFolder::LOCAL;
    folderProtocol=MailFolder::MBOX;
    accessRights=MailFolder::ALL;
	}
	else if(storageDevice.contains("sysmail_outbox"))
	{
		folderType=MailFolder::Outbox;
    messagesPlace=MailFolder::LOCAL;
    folderProtocol=MailFolder::MBOX;
    accessRights=MailFolder::ALL;
	}
	else if(storageDevice.contains("sysmail_sent"))
	{
		folderType=MailFolder::Sent;
    messagesPlace=MailFolder::LOCAL;
    folderProtocol=MailFolder::MBOX;
    accessRights=MailFolder::ALL;
	}
	else if(storageDevice.contains("sysmail"))
	{
		folderType=MailFolder::Normal;
    messagesPlace=MailFolder::LOCAL;
    folderProtocol=MailFolder::MBOX;
    accessRights=MailFolder::ALL;
	}
  else if(storageDevice.contains("imap_"))
  {
    folderType=MailFolder::Normal;
    messagesPlace=MailFolder::REMOTE;
    folderProtocol=MailFolder::IMAP4;
    accessRights=MailFolder::ALL;
  }
  else
  {
    folderType=MailFolder::Normal;
    messagesPlace=MailFolder::LOCAL;
    folderProtocol=MailFolder::MBOX;
    accessRights=MailFolder::ALL;
  }
};

int MailFolder::getFolderType() const
{
	return folderType;
}

int MailFolder::getFolderProtocol() const
{
  return folderProtocol;
}

QString MailFolder::getStorageDevice() const
{
	return storageDevice;
}

// Notify the client when we have a timeout
void MailFolder::sync()
{
  if( !syncMessages.count() )
  {
    printf("\nMailFolder::sync() : Nothing to sync!\n");
  }
  else
  {
    ServerNotifier::thisInstance()->objectCreated(syncMessages);
    syncMessages.clear();
  	ServerNotifier::thisInstance()->objectChanged(name());
  }
}
	
IndexClass *MailFolder::createMessage()
{
	// create index, set id and add to collection
	IndexClass *index=new IndexClass(this);
	syncIndexID(index);
	indexCollection.insert(index->getID(), index);
	
	// this is probably a dynamic-generated message, multipart by default
	index->setMultipartOnly(true);
	
	// create message device
	MessageDevice *dev=new MessageDevice(index);
	
	// add data (index id etc)
	MessageDescriptor &descriptor=dev->getDescriptor();
	descriptor.indexID=index->getID();
	
	// create a temporary id for the message
	// encode it
	descriptor.messageID=MIMECodec::encodeMessageId(descriptor.indexID.right(5), "aethera");
	descriptor.messageID+="@localhost";
	descriptor.uid=descriptor.messageID;
	
	descriptor.status="New";
	
	// write message id and unread mark into index
	index->setMessageID(descriptor.messageID);
	index->setUnreadMark(true);
	
	// update folder stats
	if(index->getUnreadMark()) unread++;
		
	// save index
	dev->saveDescriptor();

	// cleanup	
	delete dev;
	
	// notify client
	ServerNotifier::thisInstance()->objectCreated(name()+"/"+index->getID());
	ServerNotifier::thisInstance()->objectChanged(name());
	
	return index;	
}

void MailFolder::saveIndex()
{
	// open file
	QFile dataFile(indexFileName);
	dataFile.open(IO_WriteOnly);
	QDataStream stream(&dataFile);
	
  // save index version
	stream<<QString::number(INDEX_VERSION);
	
	// save indexes
	QDictIterator<IndexClass> it(indexCollection);
	
	IndexClass *index;
	while((index=it.current()))
	{
		stream<<(*index);
		++it;
	}
	
	// close file
	dataFile.close();

  printf("Folder %s(%p) has finished saving successfully.\n", (const char *)name(), this);
};

void MailFolder::saveIndex(IndexClass *index)
{
	// open file
	QFile dataFile(indexFileName);
	QDataStream stream;
  stream.setDevice(&dataFile);

	// check to see if this is the first index and if so save the index version
	switch( indexCollection.count() )
	{
	  case 0:
	    // remove the file if there are not mails
  		dataFile.remove();
	    break;
	  case 1:
  		dataFile.open(IO_WriteOnly);
  		stream<<QString::number(INDEX_VERSION);
    	// save index
    	stream<<(*index);	
    	// close file
    	dataFile.close();
	    break;
	  default:
      dataFile.open(IO_Append|IO_WriteOnly);
    	// save index
    	stream<<(*index);	
    	// close file
    	dataFile.close();
	    break;
	}
}

int MailFolder::getUnread() const
{
	return unread;
}

void MailFolder::setUnread(int _unread)
{
  unread=_unread;
}

void MailFolder::incrementUnread()
{
	unread++;
}

void MailFolder::decrementUnread()
{
	unread--;
}

void MailFolder::setAutoExpunge(bool expunge)
{
  autoExpunge=expunge;
}

bool MailFolder::getAutoExpunge() const
{
  return autoExpunge;
}

int MailFolder::getMessageCount() const
{
	return indexCollection.count();
}

QStringList MailFolder::getEntryList()
{
  QStringList t;
	QDictIterator<IndexClass> it(indexCollection);
	
	while(it.current())
	{
		t.append(it.currentKey());
		++it;
	}

  return t;
}

QDict<IndexClass>& MailFolder::indexIDict()
{
	return indexCollection;
}

QString MailFolder::name() const
{
	return storageDevice.mid(storageDevice.findRev('/')+1);
}

QString MailFolder::nextIndexID()
{
	QString res;
	res.sprintf("idx%09ld", ++lastIndexID);
	return res;
}

void MailFolder::syncIndexID(IndexClass *idx)
{
	idx->setID(nextIndexID());
}

void MailFolder::crossReferenceIndexSet(IndexClass *idx)
{
	GlobalConfig->setGroup("Threading");
	if(GlobalConfig->readEntry("Complete references")=="Yes")
	{
		MessageDevice *dev=new MessageDevice(idx);
		dev->loadDescriptor();
		QString parentIndexID=dev->getDescriptor().parentIndexID;
		delete dev;
		
		if(!parentIndexID.isEmpty())
		{
			// reparent and cross references for all items under parentIndexID
			QDictIterator<IndexClass> it(indexCollection);
			
			IndexClass *t;
			while((t=it.current()))
			{
				if(t->getParentID()==parentIndexID)
				{
					reparentIndex(t);
					crossReferenceIndex(t);
				}
				
				++it;
			}
		}
	}
	else
	{
		crossReferenceIndex(idx);
	}
}

void MailFolder::crossReferenceIndex(IndexClass *idx)
{
	// load message descriptor
	MessageDevice *dev=new MessageDevice(idx);
	dev->loadDescriptor();
	MessageDescriptor &descriptor=dev->getDescriptor();
	
	for(unsigned int i=0;i<descriptor.references.count();i++)
	{
		// find if reffered message exists in Magellan
		QString relatedIndexID=translateGlobalMessageID(descriptor.references[i]);
		
		if(!relatedIndexID.isNull())
		{
			// ...it does, so append the index id
			if(descriptor.relatedIndexIDList.find(relatedIndexID)==descriptor.relatedIndexIDList.end())
				descriptor.relatedIndexIDList.append(relatedIndexID);
			
			// load related message descriptor
			MessageDevice *relatedDev=new MessageDevice(findIndex(relatedIndexID));
			relatedDev->loadDescriptor(false);
			MessageDescriptor &relatedDescriptor=relatedDev->getDescriptor();
			bool saveRelated=false;
			
			// if the parent descriptor doesn't have this message in the references list then append it
			if(relatedDescriptor.references.find(idx->getMessageID())==relatedDescriptor.references.end())
			{
				relatedDescriptor.references.append(idx->getMessageID());
				saveRelated=true;
			}
			
			// add the current message
			if(relatedDescriptor.relatedIndexIDList.find(idx->getID())==relatedDescriptor.relatedIndexIDList.end())
			{
				relatedDescriptor.relatedIndexIDList.append(idx->getID());
				saveRelated=true;
			}
			
			// save related descriptor
			if(saveRelated) relatedDev->saveDescriptor();
			
			// cleanup
			delete relatedDev;
		}
	}
	
	// cleanup
	delete dev;
}

void MailFolder::reparentIndex(IndexClass *idx)
{
	// load message descriptor
	MessageDevice *dev=new MessageDevice(idx);
	dev->loadDescriptor();
	MessageDescriptor &descriptor=dev->getDescriptor();
	
	// check if this message has the "In-Reply-To" field which maps to a message in this folder
	QString parentIndexID=translateLocalMessageID(descriptor.inReplyTo);
	if(!parentIndexID.isNull())
	{
		// we found a valid parent
		descriptor.parentIndexID=parentIndexID;
		
		// save descriptor
		dev->saveDescriptor();
		
		// add message to the parent reference list
		MessageDevice *parentDevice=new MessageDevice(indexCollection[parentIndexID]);
		parentDevice->loadDescriptor(false);
		MessageDescriptor &parentDescriptor=parentDevice->getDescriptor();
		
		if(parentDescriptor.references.find(idx->getMessageID())==parentDescriptor.references.end())
		{
			parentDescriptor.references.append(idx->getMessageID());
			if(parentDescriptor.relatedIndexIDList.find(idx->getID())==parentDescriptor.relatedIndexIDList.end())
				parentDescriptor.relatedIndexIDList.append(idx->getID());
			
			parentDevice->saveDescriptor();
		}
		
		delete parentDevice;
		
		idx->setParentID(parentIndexID);
		saveIndex(idx);
		
		// notify client
		ServerNotifier::thisInstance()->hierarchyChanged(name()+"/"+idx->getID());
	}
	else
	{
		// no "true" parent was found, try heuristics
		GlobalConfig->setGroup("Threading");
		QString threadBy=GlobalConfig->readEntry("Thread by");
		QString threadAnyway=GlobalConfig->readEntry("Thread anyway");

		if(threadBy=="Subject")
		{
			// if we still have to parent, resort to the other method if the user wants that
			if(threadAnyway!="No" && !reparentBySubject(idx))
				reparentByRelated(idx);
		}
		else
		{
			// if we still have to parent, resort to the other method if the user wants that
			if(threadAnyway!="No" && !reparentByRelated(idx))
				reparentBySubject(idx);
		}
	}
	
	// cleanup
	delete dev;
}

bool MailFolder::reparentByRelated(IndexClass *idx)
{
	// load descriptor
	MessageDevice *dev=new MessageDevice(idx);
	dev->loadDescriptor();
	MessageDescriptor &descriptor=dev->getDescriptor();
	
	QString relatedIndexID, firstRelatedIndexID=QString::null;
	bool res=false;
	
	// scan the "Related-To" list for a related message that lives in the same folder	and matches the subject
	for(unsigned int i=0;i<descriptor.references.count();i++)
	{
		relatedIndexID=translateLocalMessageID(descriptor.references[i]);
		
		if(!relatedIndexID.isNull())
		{
			// set fallback to the first related message in the same folder in case subject matching fails
			if(firstRelatedIndexID.isNull()) firstRelatedIndexID=relatedIndexID;
			
			bool found=false;
			
			// load prospective parent descriptor
			MessageDevice *parentDev=new MessageDevice(indexCollection[relatedIndexID]);
			parentDev->loadDescriptor();
			
			if(subjectThreadMatch(parentDev->getDescriptor().subject, descriptor.subject))
				found=true;
			
			delete parentDev;
			
			if(found) break;
		}
		
		relatedIndexID=QString::null;
	}
	
	if(relatedIndexID.isNull())
	{
		// no related messages match the subject, therefore use the first one
		relatedIndexID=firstRelatedIndexID;
	}
	
	if(!relatedIndexID.isNull())
	{
		// eventually we found something, save it
		descriptor.parentIndexID=relatedIndexID;
		dev->saveDescriptor();
		
		// add message to the parent reference list
		MessageDevice *parentDevice=new MessageDevice(indexCollection[relatedIndexID]);
		parentDevice->loadDescriptor(false);
		MessageDescriptor &parentDescriptor=parentDevice->getDescriptor();
		
		if(parentDescriptor.references.find(idx->getMessageID())==parentDescriptor.references.end())
		{
			parentDescriptor.references.append(idx->getMessageID());
			
			if(parentDescriptor.relatedIndexIDList.find(idx->getID())==parentDescriptor.relatedIndexIDList.end())
				parentDescriptor.relatedIndexIDList.append(idx->getID());
			
			parentDevice->saveDescriptor();
		}
		
		delete parentDevice;
		res=true;
		
		idx->setParentID(relatedIndexID);
		saveIndex(idx);
		
		// notify client
		ServerNotifier::thisInstance()->hierarchyChanged(name()+"/"+idx->getID());
	}
	
	// cleanup
	delete dev;
	
	return res;
}

bool MailFolder::reparentBySubject(IndexClass *idx)
{
	// load descriptor
	MessageDevice *dev=new MessageDevice(idx);
	dev->loadDescriptor();
	MessageDescriptor &descriptor=dev->getDescriptor();
	
	bool res=false;
	
	// scan the whole folder for a parent that matches the subject and was received after the current message
	QDictIterator<IndexClass> it(indexCollection);
	IndexClass *t;
	while((t=it.current()))
	{
		// load prospective parent descriptor
		MessageDevice *parentDev=new MessageDevice(t);
		parentDev->loadDescriptor();
		MessageDescriptor &parentDescriptor=parentDev->getDescriptor();
		
		if(subjectThreadMatch(parentDescriptor.subject, descriptor.subject) &&
				DateClass((QCString)parentDescriptor.receivedDate).toQDateTime()<=DateClass((QCString)descriptor.receivedDate).toQDateTime())
		{
			descriptor.parentIndexID=it.currentKey();
			res=true;
		}
		
		delete parentDev;
		
		++it;
	}
	
	if(res)
	{
		dev->saveDescriptor();

		// load parent descriptor		
		MessageDevice *parentDevice=new MessageDevice(indexCollection[descriptor.parentIndexID]);
		parentDevice->loadDescriptor(false);
		MessageDescriptor &parentDescriptor=parentDevice->getDescriptor();
		
		// add message to the parent reference list
		if(parentDescriptor.references.find(idx->getMessageID())==parentDescriptor.references.end())
		{
			parentDescriptor.references.append(idx->getMessageID());
			
			if(parentDescriptor.relatedIndexIDList.find(idx->getID())==parentDescriptor.relatedIndexIDList.end())
				parentDescriptor.relatedIndexIDList.append(idx->getID());
			
			parentDevice->saveDescriptor();
		}
		
		delete parentDevice;
		
		idx->setParentID(descriptor.parentIndexID);
		saveIndex(idx);
		
		// notify client
		ServerNotifier::thisInstance()->hierarchyChanged(name()+"/"+idx->getID());
	}

	// cleanup	
	delete dev;
	
	return res;
}

bool MailFolder::subjectThreadMatch(QString parentSubject, QString sonSubject)
{
	GlobalConfig->setGroup("Threading");
	QStringList tokens=GlobalConfig->readEntry("Thread reply tokens");
	
	// set some default tokens if none were found
	if(!tokens.count())
	{
		tokens.append("i^\\s*re:\\s*");
		tokens.append("i^\\s*\\[re:\\]\\s*");
	}
	
	for(unsigned int i=0;i<tokens.count();i++)
	{
		bool cs=true;
		if(tokens[i][0]=='i')
		{
			cs=false;
			tokens[i]=tokens[i].mid(1);
		}
		
		QRegExp rexp(tokens[i]);
		rexp.setCaseSensitive(cs);
		
		int len;
		if(rexp.match(parentSubject, 0, &len)!=-1)
		{
			if(parentSubject.mid(len).stripWhiteSpace().lower().find(sonSubject.stripWhiteSpace().lower())==0)
				return true;
		}
	}
	
	return false;
}

QString MailFolder::translateLocalMessageID(QString messageID)
{
  if( !messageID || messageID.isNull() || messageID.isEmpty() )
    return QString::null;

	QDictIterator<IndexClass> it(indexCollection);
	
	IndexClass *t;
	
	while((t=it.current()))
	{
		if(t->getMessageID()==messageID) return it.currentKey();
		++it;
	}
	
	return QString::null;
}

QString MailFolder::translateGlobalMessageID(QString messageID)
{
	QString indexID;
	for(unsigned int i=0;i<folderList.count();i++)
	{
		indexID=folderList.at(i)->translateLocalMessageID(messageID);
		if(!indexID.isNull())
			return indexID;
	}
	
	return QString::null;
}

IndexClass *MailFolder::findIndex(const QString &id)
{
	for(unsigned int i=0;i<folderList.count();i++)
	{
		IndexClass *index;
		if((index=folderList.at(i)->indexCollection[id]))
			return index;
	}
	return 0;
}

QMap<QString, QByteArray> MailFolder::entryCacheBlock()
{
	QMap<QString, QByteArray> cacheMap;
	
	QDictIterator<IndexClass> it(indexCollection);
	IndexClass *index;
	while((index=it.current()))
	{
		MessageDevice *dev=new MessageDevice(index);
		cacheMap.insert(index->getID(), dev->getEntryCacheBlock());
		delete dev;
		++it;
	}
	
	return cacheMap;
}

void MailFolder::setPruneIndexCount(unsigned int _pruneIndexCount)
{
  pruneIndexCount=_pruneIndexCount;
}

void MailFolder::incrementPruneIndexCount()
{
  pruneIndexCount++;
}

unsigned int MailFolder::getPruneIndexCount() const
{
  return pruneIndexCount;
}

QString MailFolder::getIndexFileName() const
{
  return indexFileName;
}

QString MailFolder::getDescriptorFileName() const
{
  return descriptorFileName;
}

unsigned long MailFolder::getLastIndexID() const
{
  return lastIndexID;
}

void MailFolder::setLastIndexID(long unsigned indexId)
{
  lastIndexID=indexId;
}