• Skip to content
  • Skip to link menu
  • KDE API Reference
  • kdepimlibs-4.9.4 API Reference
  • KDE Home
  • Contact Us
 

KIMAP Library

  • kimap
fetchjob.cpp
1 /*
2  Copyright (c) 2009 Kevin Ottens <ervin@kde.org>
3 
4  This library is free software; you can redistribute it and/or modify it
5  under the terms of the GNU Library General Public License as published by
6  the Free Software Foundation; either version 2 of the License, or (at your
7  option) any later version.
8 
9  This library is distributed in the hope that it will be useful, but WITHOUT
10  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11  FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public
12  License for more details.
13 
14  You should have received a copy of the GNU Library General Public License
15  along with this library; see the file COPYING.LIB. If not, write to the
16  Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
17  02110-1301, USA.
18 */
19 
20 #include "fetchjob.h"
21 
22 #include <QtCore/QTimer>
23 #include <KDE/KDebug>
24 #include <KDE/KLocale>
25 
26 #include "job_p.h"
27 #include "message_p.h"
28 #include "session_p.h"
29 
30 namespace KIMAP
31 {
32  class FetchJobPrivate : public JobPrivate
33  {
34  public:
35  FetchJobPrivate( FetchJob *job, Session *session, const QString& name ) : JobPrivate( session, name ), q(job), uidBased(false) { }
36  ~FetchJobPrivate() { }
37 
38  void parseBodyStructure( const QByteArray &structure, int &pos, KMime::Content *content );
39  void parsePart( const QByteArray &structure, int &pos, KMime::Content *content );
40  QByteArray parseString( const QByteArray &structure, int &pos );
41  QByteArray parseSentence( const QByteArray &structure, int &pos );
42  void skipLeadingSpaces( const QByteArray &structure, int &pos );
43 
44  void emitPendings()
45  {
46  if ( pendingUids.isEmpty() ) {
47  return;
48  }
49 
50  if ( !pendingParts.isEmpty() ) {
51  emit q->partsReceived( selectedMailBox,
52  pendingUids, pendingParts );
53  }
54  if ( !pendingSizes.isEmpty() || !pendingFlags.isEmpty() ) {
55  emit q->headersReceived( selectedMailBox,
56  pendingUids, pendingSizes,
57  pendingFlags, pendingMessages );
58  }
59  if ( !pendingMessages.isEmpty() ) {
60  emit q->messagesReceived( selectedMailBox,
61  pendingUids, pendingMessages );
62  }
63 
64  pendingUids.clear();
65  pendingMessages.clear();
66  pendingParts.clear();
67  pendingSizes.clear();
68  pendingFlags.clear();
69  }
70 
71  FetchJob * const q;
72 
73  ImapSet set;
74  bool uidBased;
75  FetchJob::FetchScope scope;
76  QString selectedMailBox;
77 
78  QTimer emitPendingsTimer;
79  QMap<qint64, MessagePtr> pendingMessages;
80  QMap<qint64, MessageParts> pendingParts;
81  QMap<qint64, MessageFlags> pendingFlags;
82  QMap<qint64, qint64> pendingSizes;
83  QMap<qint64, qint64> pendingUids;
84  };
85 }
86 
87 using namespace KIMAP;
88 
89 FetchJob::FetchJob( Session *session )
90  : Job( *new FetchJobPrivate(this, session, i18n("Fetch")) )
91 {
92  Q_D(FetchJob);
93  d->scope.mode = FetchScope::Content;
94  connect( &d->emitPendingsTimer, SIGNAL(timeout()),
95  this, SLOT(emitPendings()) );
96 }
97 
98 FetchJob::~FetchJob()
99 {
100 }
101 
102 void FetchJob::setSequenceSet( const ImapSet &set )
103 {
104  Q_D(FetchJob);
105  Q_ASSERT( !set.toImapSequenceSet().trimmed().isEmpty() );
106  d->set = set;
107 }
108 
109 ImapSet FetchJob::sequenceSet() const
110 {
111  Q_D(const FetchJob);
112  return d->set;
113 }
114 
115 void FetchJob::setUidBased(bool uidBased)
116 {
117  Q_D(FetchJob);
118  d->uidBased = uidBased;
119 }
120 
121 bool FetchJob::isUidBased() const
122 {
123  Q_D(const FetchJob);
124  return d->uidBased;
125 }
126 
127 void FetchJob::setScope( const FetchScope &scope )
128 {
129  Q_D(FetchJob);
130  d->scope = scope;
131 }
132 
133 FetchJob::FetchScope FetchJob::scope() const
134 {
135  Q_D(const FetchJob);
136  return d->scope;
137 }
138 
139 QMap<qint64, MessagePtr> FetchJob::messages() const
140 {
141  return QMap<qint64, MessagePtr>();
142 }
143 
144 QMap<qint64, MessageParts> FetchJob::parts() const
145 {
146  return QMap<qint64, MessageParts>();
147 }
148 
149 QMap<qint64, MessageFlags> FetchJob::flags() const
150 {
151  return QMap<qint64, MessageFlags>();
152 }
153 
154 QMap<qint64, qint64> FetchJob::sizes() const
155 {
156  return QMap<qint64, qint64>();
157 }
158 
159 QMap<qint64, qint64> FetchJob::uids() const
160 {
161  return QMap<qint64, qint64>();
162 }
163 
164 void FetchJob::doStart()
165 {
166  Q_D(FetchJob);
167 
168  QByteArray parameters = d->set.toImapSequenceSet()+' ';
169  Q_ASSERT( !parameters.trimmed().isEmpty() );
170 
171  switch ( d->scope.mode ) {
172  case FetchScope::Headers:
173  if ( d->scope.parts.isEmpty() ) {
174  parameters+="(RFC822.SIZE INTERNALDATE BODY.PEEK[HEADER.FIELDS (TO FROM MESSAGE-ID REFERENCES IN-REPLY-TO SUBJECT DATE)] FLAGS UID)";
175  } else {
176  parameters+='(';
177  foreach ( const QByteArray &part, d->scope.parts ) {
178  parameters+="BODY.PEEK["+part+".MIME] ";
179  }
180  parameters+="UID)";
181  }
182  break;
183  case FetchScope::Flags:
184  parameters+="(FLAGS UID)";
185  break;
186  case FetchScope::Structure:
187  parameters+="(BODYSTRUCTURE UID)";
188  break;
189  case FetchScope::Content:
190  if ( d->scope.parts.isEmpty() ) {
191  parameters+="(BODY.PEEK[] UID)";
192  } else {
193  parameters+='(';
194  foreach ( const QByteArray &part, d->scope.parts ) {
195  parameters+="BODY.PEEK["+part+"] ";
196  }
197  parameters+="UID)";
198  }
199  break;
200  case FetchScope::Full:
201  parameters+="(RFC822.SIZE INTERNALDATE BODY.PEEK[] FLAGS UID)";
202  break;
203  case FetchScope::HeaderAndContent:
204  if ( d->scope.parts.isEmpty() ) {
205  parameters+="(BODY.PEEK[] FLAGS UID)";
206  } else {
207  parameters+="(BODY.PEEK[HEADER.FIELDS (TO FROM MESSAGE-ID REFERENCES IN-REPLY-TO SUBJECT DATE)]";
208  foreach ( const QByteArray &part, d->scope.parts ) {
209  parameters+=" BODY.PEEK["+part+".MIME] BODY.PEEK["+part+"]"; //krazy:exclude=doublequote_chars
210  }
211  parameters+=" FLAGS UID)";
212  }
213  break;
214  }
215 
216  QByteArray command = "FETCH";
217  if ( d->uidBased ) {
218  command = "UID "+command;
219  }
220 
221  d->emitPendingsTimer.start( 100 );
222  d->selectedMailBox = d->m_session->selectedMailBox();
223  d->tags << d->sessionInternal()->sendCommand( command, parameters );
224 }
225 
226 void FetchJob::handleResponse( const Message &response )
227 {
228  Q_D(FetchJob);
229 
230  // We can predict it'll be handled by handleErrorReplies() so stop
231  // the timer now so that result() will really be the last emitted signal.
232  if ( !response.content.isEmpty()
233  && d->tags.size() == 1
234  && d->tags.contains( response.content.first().toString() ) ) {
235  d->emitPendingsTimer.stop();
236  d->emitPendings();
237  }
238 
239  if (handleErrorReplies(response) == NotHandled ) {
240  if ( response.content.size() == 4
241  && response.content[2].toString()=="FETCH"
242  && response.content[3].type()==Message::Part::List ) {
243 
244  qint64 id = response.content[1].toString().toLongLong();
245  QList<QByteArray> content = response.content[3].toList();
246 
247  MessagePtr message( new KMime::Message );
248  bool shouldParseMessage = false;
249  MessageParts parts;
250 
251  for ( QList<QByteArray>::ConstIterator it = content.constBegin();
252  it!=content.constEnd(); ++it ) {
253  QByteArray str = *it;
254  ++it;
255 
256  if ( it==content.constEnd() ) { // Uh oh, message was truncated?
257  kWarning() << "FETCH reply got truncated, skipping.";
258  break;
259  }
260 
261  if ( str=="UID" ) {
262  d->pendingUids[id] = it->toLongLong();
263  } else if ( str=="RFC822.SIZE" ) {
264  d->pendingSizes[id] = it->toLongLong();
265  } else if ( str=="INTERNALDATE" ) {
266  message->date()->setDateTime( KDateTime::fromString( *it, KDateTime::RFCDate ) );
267  } else if ( str=="FLAGS" ) {
268  if ( (*it).startsWith('(') && (*it).endsWith(')') ) {
269  QByteArray str = *it;
270  str.chop(1);
271  str.remove(0, 1);
272  d->pendingFlags[id] = str.split(' ');
273  } else {
274  d->pendingFlags[id] << *it;
275  }
276  } else if ( str=="BODYSTRUCTURE" ) {
277  int pos = 0;
278  d->parseBodyStructure(*it, pos, message.get());
279  message->assemble();
280  d->pendingMessages[id] = message;
281  } else if ( str.startsWith( "BODY[") ) { //krazy:exclude=strings
282  if ( !str.endsWith(']') ) { // BODY[ ... ] might have been split, skip until we find the ]
283  while ( !(*it).endsWith(']') ) ++it;
284  ++it;
285  }
286 
287  int index;
288  if ( (index=str.indexOf("HEADER"))>0 || (index=str.indexOf("MIME"))>0 ) { // headers
289  if ( str[index-1]=='.' ) {
290  QByteArray partId = str.mid( 5, index-6 );
291  if ( !parts.contains( partId ) ) {
292  parts[partId] = ContentPtr( new KMime::Content );
293  }
294  parts[partId]->setHead(*it);
295  parts[partId]->parse();
296  d->pendingParts[id] = parts;
297  } else {
298  message->setHead(*it);
299  shouldParseMessage = true;
300  }
301  } else { // full payload
302  if ( str=="BODY[]" ) {
303  message->setContent( KMime::CRLFtoLF(*it) );
304  shouldParseMessage = true;
305 
306  d->pendingMessages[id] = message;
307  } else {
308  QByteArray partId = str.mid( 5, str.size()-6 );
309  if ( !parts.contains( partId ) ) {
310  parts[partId] = ContentPtr( new KMime::Content );
311  }
312  parts[partId]->setBody(*it);
313  parts[partId]->parse();
314 
315  d->pendingParts[id] = parts;
316  }
317  }
318  }
319  }
320 
321  if ( shouldParseMessage ) {
322  message->parse();
323  }
324 
325  // For the headers mode the message is built in several
326  // steps, hence why we wait it to be done until putting it
327  // in the pending queue.
328  if ( d->scope.mode == FetchScope::Headers || d->scope.mode == FetchScope::HeaderAndContent ) {
329  d->pendingMessages[id] = message;
330  }
331  }
332  }
333 }
334 
335 void FetchJobPrivate::parseBodyStructure(const QByteArray &structure, int &pos, KMime::Content *content)
336 {
337  skipLeadingSpaces(structure, pos);
338 
339  if ( structure[pos]!='(' ) {
340  return;
341  }
342 
343  pos++;
344 
345 
346  if ( structure[pos]!='(' ) { // simple part
347  pos--;
348  parsePart( structure, pos, content );
349  } else { // multi part
350  content->contentType()->setMimeType("MULTIPART/MIXED");
351  while ( pos<structure.size() && structure[pos]=='(' ) {
352  KMime::Content *child = new KMime::Content;
353  content->addContent( child );
354  parseBodyStructure( structure, pos, child );
355  child->assemble();
356  }
357 
358  QByteArray subType = parseString( structure, pos );
359  content->contentType()->setMimeType( "MULTIPART/"+subType );
360 
361  QByteArray parameters = parseSentence( structure, pos ); // FIXME: Read the charset
362  if (parameters.contains("BOUNDARY") ) {
363  content->contentType()->setBoundary(parameters.remove(0, parameters.indexOf("BOUNDARY") + 11).split('\"')[0]);
364  }
365 
366  QByteArray disposition = parseSentence( structure, pos );
367  if ( disposition.contains("INLINE") ) {
368  content->contentDisposition()->setDisposition( KMime::Headers::CDinline );
369  } else if ( disposition.contains("ATTACHMENT") ) {
370  content->contentDisposition()->setDisposition( KMime::Headers::CDattachment );
371  }
372 
373  parseSentence( structure, pos ); // Ditch the body language
374  }
375 
376  // Consume what's left
377  while ( pos<structure.size() && structure[pos]!=')' ) {
378  skipLeadingSpaces( structure, pos );
379  parseSentence( structure, pos );
380  skipLeadingSpaces( structure, pos );
381  }
382 
383  pos++;
384 }
385 
386 void FetchJobPrivate::parsePart( const QByteArray &structure, int &pos, KMime::Content *content )
387 {
388  if ( structure[pos]!='(' ) {
389  return;
390  }
391 
392  pos++;
393 
394  QByteArray mainType = parseString( structure, pos );
395  QByteArray subType = parseString( structure, pos );
396 
397  content->contentType()->setMimeType( mainType+'/'+subType );
398 
399  parseSentence( structure, pos ); // Ditch the parameters... FIXME: Read it to get charset and name
400  parseString( structure, pos ); // ... and the id
401 
402  content->contentDescription()->from7BitString( parseString( structure, pos ) );
403 
404  parseString( structure, pos ); // Ditch the encoding too
405  parseString( structure, pos ); // ... and the size
406  parseString( structure, pos ); // ... and the line count
407 
408  QByteArray disposition = parseSentence( structure, pos );
409  if ( disposition.contains("INLINE") ) {
410  content->contentDisposition()->setDisposition( KMime::Headers::CDinline );
411  } else if ( disposition.contains("ATTACHMENT") ) {
412  content->contentDisposition()->setDisposition( KMime::Headers::CDattachment );
413  }
414  if ( (content->contentDisposition()->disposition() == KMime::Headers::CDattachment
415  || content->contentDisposition()->disposition() == KMime::Headers::CDinline)
416  && disposition.contains("FILENAME") ) {
417  QByteArray filename = disposition.remove(0, disposition.indexOf("FILENAME") + 11).split('\"')[0];
418  content->contentDisposition()->setFilename( filename );
419  }
420 
421  // Consume what's left
422  while ( pos<structure.size() && structure[pos]!=')' ) {
423  skipLeadingSpaces( structure, pos );
424  parseSentence( structure, pos );
425  skipLeadingSpaces( structure, pos );
426  }
427 }
428 
429 QByteArray FetchJobPrivate::parseSentence( const QByteArray &structure, int &pos )
430 {
431  QByteArray result;
432  int stack = 0;
433 
434  skipLeadingSpaces( structure, pos );
435 
436  if ( structure[pos]!='(' ) {
437  return parseString( structure, pos );
438  }
439 
440  int start = pos;
441 
442  do {
443  switch ( structure[pos] ) {
444  case '(':
445  pos++;
446  stack++;
447  break;
448  case ')':
449  pos++;
450  stack--;
451  break;
452  case '[':
453  pos++;
454  stack++;
455  break;
456  case ']':
457  pos++;
458  stack--;
459  break;
460  default:
461  skipLeadingSpaces(structure, pos);
462  parseString(structure, pos);
463  skipLeadingSpaces(structure, pos);
464  break;
465  }
466  } while ( pos<structure.size() && stack!=0 );
467 
468  result = structure.mid( start, pos - start );
469 
470  return result;
471 }
472 
473 QByteArray FetchJobPrivate::parseString( const QByteArray &structure, int &pos )
474 {
475  QByteArray result;
476 
477  skipLeadingSpaces( structure, pos );
478 
479  int start = pos;
480  bool foundSlash = false;
481 
482  // quoted string
483  if ( structure[pos] == '"' ) {
484  pos++;
485  Q_FOREVER {
486  if ( structure[pos] == '\\' ) {
487  pos+= 2;
488  foundSlash = true;
489  continue;
490  }
491  if ( structure[pos] == '"' ) {
492  result = structure.mid( start+1, pos - start - 1);
493  pos++;
494  break;
495  }
496  pos++;
497  }
498  } else { // unquoted string
499  Q_FOREVER {
500  if ( structure[pos] == ' ' || structure[pos] == '(' || structure[pos] == ')' || structure[pos] == '[' || structure[pos] == ']' || structure[pos] == '\n' || structure[pos] == '\r' || structure[pos] == '"') {
501  break;
502  }
503  if (structure[pos] == '\\')
504  foundSlash = true;
505  pos++;
506  }
507 
508  result = structure.mid( start, pos - start );
509 
510  // transform unquoted NIL
511  if ( result == "NIL" )
512  result.clear();
513  }
514 
515  // simplify slashes
516  if ( foundSlash ) {
517  while ( result.contains( "\\\"" ) )
518  result.replace( "\\\"", "\"" );
519  while ( result.contains( "\\\\" ) )
520  result.replace( "\\\\", "\\" );
521  }
522 
523  return result;
524 }
525 
526 void FetchJobPrivate::skipLeadingSpaces( const QByteArray &structure, int &pos )
527 {
528  while ( structure[pos]==' ' && pos<structure.size() ) pos++;
529 }
530 
531 #include "fetchjob.moc"
This file is part of the KDE documentation.
Documentation copyright © 1996-2012 The KDE developers.
Generated on Tue Dec 11 2012 12:12:46 by doxygen 1.8.1.2 written by Dimitri van Heesch, © 1997-2006

KDE's Doxygen guidelines are available online.

KIMAP Library

Skip menu "KIMAP Library"
  • Main Page
  • Namespace List
  • Namespace Members
  • Alphabetical List
  • Class List
  • Class Hierarchy
  • Class Members
  • File List
  • Related Pages

kdepimlibs-4.9.4 API Reference

Skip menu "kdepimlibs-4.9.4 API Reference"
  • akonadi
  •   contact
  •   kmime
  • kabc
  • kalarmcal
  • kblog
  • kcal
  • kcalcore
  • kcalutils
  • kholidays
  • kimap
  • kioslave
  •   imap4
  •   mbox
  •   nntp
  • kldap
  • kmbox
  • kmime
  • kontactinterface
  • kpimidentities
  • kpimtextedit
  •   richtextbuilders
  • kpimutils
  • kresources
  • ktnef
  • kxmlrpcclient
  • mailtransport
  • microblog
  • qgpgme
  • syndication
  •   atom
  •   rdf
  •   rss2
Report problems with this website to our bug tracking system.
Contact the specific authors with questions and comments about the page contents.

KDE® and the K Desktop Environment® logo are registered trademarks of KDE e.V. | Legal